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

JavaScript中从fetch返回的Promise提取数据时出现undefined的问题咨询

如何正确从Promise中提取异步数据?

你的问题核心在于同步函数无法直接获取异步操作的结果——咱们一步一步拆解问题出在哪,再给出解决方案。

为什么你的代码会返回undefined?

看你的getCoordinates函数:

function getCoordinates(pluscode) { 
  let geoinfo; 
  fetchCoordinates(pluscode).then(info => {geoinfo = info}) 
  return geoinfo 
} 

JavaScript的异步操作是非阻塞的:当代码执行到fetchCoordinates(pluscode).then(...)时,浏览器会去后台发起请求,同时继续执行后面的return geoinfo。这时候then里的回调函数还没触发(因为请求还没完成),geoinfo还是你初始化时的undefined,所以自然返回了undefined。

而你改成console.log(info)能正确打印,是因为then的回调会等到Promise状态变为resolved(也就是请求完成、数据返回后)才执行,这时候info已经是你要的对象了。

解决方法:让异步操作的结果能被正确获取

你有两种主流的解决方式,本质都是遵循异步操作的规则来处理结果:

方法1:把getCoordinates改成异步函数,使用await获取结果

既然fetchCoordinates是异步函数,那getCoordinates也应该是异步的,这样就能用await等待Promise完成:

async function fetchCoordinates(pluscode) { 
  let response = await fetch(url.replace("${pluscode}", pluscode)); 
  return await response.json(); 
} 

// 改成async函数
async function getCoordinates(pluscode) { 
  // 直接等待fetchCoordinates的结果并返回
  return await fetchCoordinates(pluscode);
} 

// 调用时注意:await必须在async函数内部使用
async function handleCoordinates() {
  const geoinfo = await getCoordinates("{{ place.pluscode }}");
  console.log(geoinfo); // 这里就能拿到正确的对象了
  // 在这里做你需要的后续操作,比如渲染页面、计算等
}
handleCoordinates();

方法2:让getCoordinates返回Promise,调用时用then处理结果

如果你不想把getCoordinates改成async函数,也可以让它直接返回Promise,然后在调用时通过then获取数据:

function getCoordinates(pluscode) { 
  // 直接返回fetchCoordinates的Promise
  return fetchCoordinates(pluscode);
} 

// 调用时用then处理结果
getCoordinates("{{ place.pluscode }}").then(geoinfo => {
  console.log(geoinfo);
  // 在这里处理geoinfo,比如赋值给变量、更新DOM等
});

关键提醒

异步操作的结果永远不能同步返回——你必须通过await(仅限async函数内)或者then链式调用的方式,等到Promise完成后再处理数据。任何试图在同步函数里直接获取异步结果的行为,都会因为操作还没完成而拿到undefined或者未完成的Promise对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 01:57:45