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

如何获取async异步函数输出?调用返回Promise{<pending>}如何解决

问题根源

你遇到的问题来自两个核心认知偏差和代码错误:

  • async函数永远返回Promise:async/await只是异步代码的语法糖,await只会暂停当前async函数内部的执行流,不会阻塞函数外部的同步代码。所有被async标记的函数,无论内部逻辑如何,调用后都会立刻返回一个Promise对象,你在同步上下文里直接打印getData()的调用结果时,内部的fetch请求还没完成,此时Promise自然处于<pending>挂起状态。
  • 返回值写法存在语法bug:你写的return (latitude, longitude)触发了JS的逗号操作符规则,括号内的表达式会从左到右执行,但最终只会返回最后一个表达式的值——也就是就算Promise正常兑现,你也只能拿到longitude,拿不到latitude。
正确获取返回值的方案

你需要在Promise兑现后再读取结果,首先要修正getData的返回值,改成返回包含两个字段的对象:

const issURL = 'someUrl';
async function getData() {
    const res = await fetch(issURL);
    const data = await res.json();
    const { latitude, longitude } = data;
    // 修正返回值,返回对象承载两个字段
    return { latitude, longitude };
}

方案1:使用await调用(推荐)

await只能在async函数内部、或者ES模块的顶层作用域使用,最常见的写法是包一层异步入口函数:

async function main() {
    try {
        const { latitude, longitude } = await getData();
        console.log('纬度:', latitude, '经度:', longitude);
    } catch (err) {
        // 必须加错误捕获,处理网络请求失败、JSON解析失败等异常
        console.error('获取位置失败:', err);
    }
}
main();

如果你的运行环境支持顶层await(现代浏览器ES模块、Node.js 14.6.0及以上版本),可以省略外层函数直接写:

try {
    const { latitude, longitude } = await getData();
    console.log(latitude, longitude);
} catch (err) {
    console.error(err);
}

方案2:使用Promise原生then方法

如果不想额外写async函数,可以直接用Promise的then链式调用获取结果:

getData()
    .then(({ latitude, longitude }) => {
        console.log(latitude, longitude);
    })
    .catch(err => {
        console.error('获取位置失败:', err);
    });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 09:12:19