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

使用async/await从Promise中提取数据的问题

问题分析与解决

你的核心问题是:你在外部错误地对async函数返回的结果调用了res.json()——你的async函数内部已经完成了fetch的Response转json、数据筛选的操作,返回的Promise最终解析为你要的目标数据,而不是fetch返回的Response对象,所以调用json()会报错,自然拿不到正确数据。

你的两种写法的具体问题

  • 第一种写法:my_async_function().then(res => res.json()),这里的res是函数return的bar.find(...)结果(普通对象或undefined),它没有json()方法,直接调用会抛出错误。
  • 第二种写法:同样错误调用了res.json(),而且data是在异步回调中赋值的,同步代码中直接访问data时,回调还没执行,所以它始终是undefined。

正确写法

写法1:用.then()处理结果

const my_async_function = async() => {
    try {
        const foo = await fetch(`api/foo/uuid`).then(res => res.json());
        const bar = await fetch(`api/bar/${foo.uuid}`).then(res => res.json());
        return bar.find(el => el.name === 'hello');
    }
    catch (err) {
        console.error(err);
        // 重新抛出错误,让外部能捕获到异常
        throw err;
    }
}

my_async_function().then(data => {
    // data就是你要的最终筛选后的数据
    console.log(data);
    // 在这里执行后续依赖data的逻辑
}).catch(err => {
    // 统一处理错误
    console.error("获取数据失败:", err);
});

写法2:用async/await统一风格(更推荐)

可以把内部的.then(res => res.json())也换成await,让代码风格更统一:

const my_async_function = async() => {
    try {
        const fooResponse = await fetch(`api/foo/uuid`);
        const foo = await fooResponse.json();
        
        const barResponse = await fetch(`api/bar/${foo.uuid}`);
        const bar = await barResponse.json();
        
        return bar.find(el => el.name === 'hello');
    }
    catch (err) {
        console.error(err);
        throw err;
    }
}

// 在自执行async函数中调用,避免全局上下文无法用await
(async () => {
    try {
        const data = await my_async_function();
        console.log(data);
        // 后续逻辑写在这里
    } catch (err) {
        console.error("获取数据失败:", err);
    }
})();

额外注意事项

  • 原函数的catch块如果只打印错误而不重新抛出,外部的Promise会解析为undefined,不利于排查错误,所以建议在catch中throw err。
  • 异步操作的结果只能在异步回调(.then()内)或await之后访问,同步代码中直接访问会拿到初始值(比如undefined)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 09:50:18