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

使用Fetch API发起带错误校验的请求后如何在async函数外获取可用数据

原因说明

你现在拿到pending状态的Promise是因为async函数的返回值天生是Promise类型,你调用时没有等待异步请求完成,直接打印就会显示pending状态,必须等待Promise状态变更为fulfilled后才能拿到实际的接口返回数据。

可用解决方案

方案1:所有依赖接口数据的逻辑放在async函数内部(最推荐)

把需要用到data的逻辑都放到await语句之后执行,保证执行时数据已经返回:

const fetch = require('node-fetch')
const url = 'https://employeedetails.free.beeceptor.com/my/api/path'

async function getData(url){
    try {
        const response = await fetch(url)
        if (!response.ok) {
            throw new Error("why did I become a software engineer?");
        }
        return await response.json();
    }
    catch (error) {
        console.log(error);
        // 建议加上错误兜底返回,避免上层拿到undefined
        return null
    }
}

// 把后续逻辑封装到另一个async函数里
async function main() {
    const data = await getData(url);
    // 此处可正常使用data,保证已经拿到返回值
    console.log(data);
    // 其他用到data的逻辑都可以写在这里
}

main()

方案2:用.then()链式调用处理返回值

不想额外封装async函数的话,可以直接用Promise原型的then方法接收返回值:

const fetch = require('node-fetch')
const url = 'https://employeedetails.free.beeceptor.com/my/api/path'

async function getData(url){
    try {
        const response = await fetch(url)
        if (!response.ok) {
            throw new Error("why did I become a software engineer?");
        }
        return await response.json();
    }
    catch (error) {
        console.log(error);
        return null
    }
}

getData(url).then(data => {
    // 该作用域内可正常使用data
    console.log(data)
})

方案3:使用顶层await(Node.js 14.8+ 支持)

如果你的Node.js版本高于14.8,直接在全局作用域用await即可,不需要额外封装函数:

const fetch = require('node-fetch')
const url = 'https://employeedetails.free.beeceptor.com/my/api/path'

async function getData(url){
    try {
        const response = await fetch(url)
        if (!response.ok) {
            throw new Error("why did I become a software engineer?");
        }
        return await response.json();
    }
    catch (error) {
        console.log(error);
        return null
    }
}

const data = await getData(url);
console.log(data);
注意事项
  • 不要尝试把异步返回的值同步赋值给全局变量后在同步代码里调用,JavaScript的事件循环机制会保证同步代码先执行,此时异步请求还没返回,拿到的永远是初始值。
  • 你现有的catch逻辑只会打印错误,最终会返回undefined,建议加上兜底返回值或者把错误抛出给上层处理,避免后续逻辑报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:06:02