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

JavaScript中API返回数据赋值变量报错问题求助

异步API调用导致的数据访问问题分析与解决

核心问题:异步操作的执行顺序

你的get_data()函数里用了fetch发起异步请求,这类操作不会阻塞代码执行——函数会先走完同步逻辑,直接返回undefined,这时候外部执行var data = get_data()拿到的是undefined,自然会报“Cannot read properties of undefined (reading 'city')”的错。而函数内部能正常打印数据,是因为打印语句写在.then()回调里,这部分代码会等到API返回数据后才执行,此时已经拿到了完整的响应数据。

两种解决办法

方法1:用async/await简化异步逻辑

把get_data改成异步函数,调用时通过await等待数据返回:

async function get_data() {
  const res = await fetch('目标API地址');
  const data = await res.json();
  console.log(data.city); // 内部正常打印
  return data;
}

// 必须在async函数内使用await
async function processData() {
  const data = await get_data();
  console.log(data.city); // 外部可正常访问
}
processData();

方法2:返回Promise,外部用.then()处理

如果不想用async/await,让函数直接返回Promise对象,外部通过回调获取数据:

function get_data() {
  return fetch('目标API地址')
    .then(res => res.json())
    .then(data => {
      console.log(data.city);
      return data;
    });
}

// 外部调用时通过then接收数据
get_data().then(data => {
  console.log(data.city); // 正常访问属性
});

关键逻辑梳理

  • 异步请求发起后,JS引擎会继续执行后续代码,不会等待API响应
  • 函数内部的.then()是异步回调,只有当API返回数据后才会触发,所以能拿到有效数据
  • 直接赋值var data = get_data()时,函数还没等到API结果就已经返回,因此data是undefined

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 05:34:59