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

Node.js中异步JavaScript函数返回undefined问题

问题原因及修复方案

你的cloudVerify函数返回undefined的核心原因是:外层async函数没有返回axios请求的Promise结果。你在then回调里return的1,只是这个回调函数的返回值,并没有传递到外层的cloudVerify函数中,所以整个函数执行完后默认返回undefined。

修复步骤:

  • 给await axios.get(...)这一行加上return,让外层async函数接收并返回then链的结果
  • 在catch回调里也返回一个明确的值(比如0),避免请求出错时函数依然返回undefined

修改后的代码:

async function cloudVerify(y, x) {
  const url = `https://**myAPI**.execute-api.us-west-2.amazonaws.com/items/${y}`;
  console.log(url);
  // 加上return,把axios请求的Promise结果返回给外层async函数
  return await axios
    .get(url)
    .then((res) => {
      const headerDate =
        res.headers && res.headers.date ? res.headers.date : "no response date";
      console.log("Status Code:", res.status);
      console.log("Date in Response header:", headerDate);

      const receivedData = res.data;
      const receivedItem = receivedData.Item;
      console.log(
        `Got user with id: ${receivedItem.id}, hash: ${receivedItem.hash}`
      );
      console.log(`received item hash is ${receivedItem.hash}`);
      console.log(`meta is : ${x}, hash: ${receivedItem.hash}`);
      // 这里的return会成为then链的最终返回值,被外层的await接收
      // 可以替换成你的对比逻辑,比如:return receivedItem.hash === x ? 1 : 0;
      return 1;
    })
    .catch((err) => {
      console.log("Error: ", err.message);
      // 请求出错时返回0,保证函数始终有明确返回值
      return 0;
    });
}

补充说明

按照你的需求,后续可以把return 1替换成实际的对比逻辑,比如判断receivedItem.hash和输入x是否一致,返回1或0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 00:05:26