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

Node.js中方法内调用fetch接口无法正常返回值的问题如何解决?

问题核心原因

fetch是异步操作,调用包含fetch的函数后返回的是Promise实例,你没有等待异步请求执行完成就直接返回结果,所以无法拿到接口返回的实际数据。

现有代码的其他错误

  • catch方法接收的参数必须是回调函数,你当前直接传入字符串,无法完成异常捕获逻辑
  • return res.status(200).send()之后的randomResponse = []代码永远不会执行,属于无效代码
  • birthYear初始定义为字符串类型,直接和数字做比较存在隐式转换风险,建议先转成数字类型再判断
  • 目前kanye-quote对应的请求地址和chuck-norris-joke完全一致,不符合业务命名预期,可按需更换为对应接口地址

修正方案

你需要把外层的处理函数改为async函数,调用异步方法前加await等待执行完成,修正后的代码如下:

API定义部分

let name = 'Abc';
let birthYear = "1994";
let randomResponse = [];

const APIcallsObject = {
    "chuck-norris-joke": async () => {
        try {
            const response = await fetch("https://api.chucknorris.io/jokes/random");
            const data = await response.json();
            return data.value;
        } catch (err) {
            throw new Error(`Couldn't fetch or parse chuck-norris-joke data`);
        }
    },
    "kanye-quote": async () => {
        try {
            // 此处可替换为kanye对应接口地址
            const response = await fetch("https://api.chucknorris.io/jokes/random");
            const data = await response.json();
            return data.value;
        } catch (err) {
            throw new Error(`Couldn't fetch or parse kanye-quote data`);
        }
    },
    "name-sum": (name, birthYear) => {
        let sum = 0;
        for (let index = 0; index < name.length; index++)
            sum += name.toLowerCase().charCodeAt(index) - 96;
        return `sum = ${sum}`;
    },
}

逻辑执行部分

注意外层处理函数需要加async关键字,以Express路由为例:

app.get('/your/api/path', async (req, res) => {
    checkMatches(name, Number(birthYear), randomResponse);
    let response = randomResponse[Math.floor(Math.random() * randomResponse.length)];
    // 加await等待异步请求执行完成
    const result = await APIcallsObject[response](name, birthYear);
    res.status(200).send({"type" : response ,"result" : result});
    randomResponse = [];
})

checkMatches函数

const checkMatches = (name, birthYear, randomResponse) => {
    if (birthYear <= 2000) randomResponse.push("chuck-norris-joke");
    if (birthYear > 2000 && (name[0] != 'A' || name[0] != 'Z')) randomResponse.push("kanye-quote");
    if (name[0] != 'Q') randomResponse.push("name-sum");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 18:00:04