You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将fetch返回的对象数组传递给调用函数(Django与JS)

问题根源与解决方案

你的核心问题是radiocontacttownslist函数没有正确返回异步操作的结果——fetch是异步API,它的结果只能通过Promise传递,你之前的写法要么没返回Promise链,要么在fetch的回调里return数据(那只是回调函数的返回值,不是外层函数的),导致外部await拿到undefined。

正确的函数写法

方式1:使用Promise链式调用

function radiocontacttownslist() {
  // 必须return整个fetch调用的Promise链
  return fetch('/你的Django接口地址/')
    .then(response => {
      // 先校验请求是否成功
      if (!response.ok) {
        throw new Error(`请求失败:${response.status}`);
      }
      return response.json(); // 解析返回的JSON为对象数组
    })
    .then(data => {
      console.log('获取到的数据:', data);
      return data; // 将数据返回,供外部获取
    })
    .catch(error => {
      console.error('获取数据出错:', error);
      throw error; // 抛出错误,让调用方可以处理
    });
}

方式2:使用async/await简化(更易读)

async function radiocontacttownslist() {
  try {
    const response = await fetch('/你的Django接口地址/');
    if (!response.ok) {
      throw new Error(`请求失败:${response.status}`);
    }
    const data = await response.json();
    console.log('获取到的数据:', data);
    return data;
  } catch (error) {
    console.error('获取数据出错:', error);
    throw error;
  }
}

主函数的正确调用方式

主函数必须是async函数,用await接收异步结果:

async function mainMapFunction() {
  try {
    const townsData = await radiocontacttownslist();
    // 这里就能拿到正常的对象数组,执行你的映射逻辑
    console.log('主函数拿到的数据:', townsData);
  } catch (error) {
    // 统一处理错误,比如提示用户
    console.error('主函数执行出错:', error);
  }
}

// 调用主函数
mainMapFunction();

为什么字符串/数字能正常返回?

因为返回字符串/数字是同步操作,函数直接return就能把值传递出去;但fetch是异步操作,它的结果不会立即返回,必须通过Promise来“等待”结果就绪后再传递,同步的return方式根本拿不到异步数据。

内容的提问来源于stack exchange,提问作者Gidgey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 07:17:37