You need to enable JavaScript to run this app. Node.js异步循环调用axios返回全undefined数组问题排查求助
优惠活动
大模型
产品
解决方案
定价
更多

Node.js异步循环调用axios返回全undefined数组问题排查求助

问题原因

你的代码核心问题是getItem函数没有正确返回异步请求的结果,导致调用时拿到的都是undefined,具体有两个错误点:

  • getItem没有显式返回值,内部.then()回调里的return res2.data只属于Promise链内部的返回,没有传递到getItem的外层返回值中,所以调用getItem拿到的永远是成功状态的undefined。
  • 混用async/await和.then()链式调用的写法,大幅提升了返回值传递的复杂度,很容易漏写return导致值丢失。
修复方案

推荐统一使用async/await语法,减少嵌套同时避免返回值丢失问题:

修正getItem函数

const getItem = async (Name) => {
  // 第一个请求直接用await拿响应结果
  const res1 = await axios.get(url1 + Name);
  // 注意:原代码直接拼接res1,实际需要取响应体的话要写res1.data,根据你的接口返回调整即可
  const url3 = url2 + res1.data;
  const res2 = await axios.get(url3);
  console.log(res2.data);
  // 显式返回结果,外层调用才能拿到值
  return res2.data;
};

优化getAll函数

原来的串行循环请求性能较低,不需要严格按顺序请求的话可以用Promise.all并行处理,速度更快:

// 并行版本(推荐)
const getAll = async (Arr) => {
  return Promise.all(Arr.map(Name => getItem(Name)));
}

// 如果必须按顺序串行请求,保留原有写法也可以,只要getItem正确返回值就不会出问题
const getAllSerial = async (Arr) => {
  const A = [];
  for (const Name of Arr) {
    const res1 = await getItem(Name);
    console.log("res1: "+res1);
    A.push(res1);
  }
  return A;
}

兼容.then写法的修正方案

如果你不想改现有链式调用的写法,只要补全所有层级的return即可:

const getItem = (Name) => {
  // 外层返回整个Promise链
  return axios.get(url1+Name)
  .then((res1) => {
    const url3 = url2 + res1.data;
    // 内层也要返回第二个axios的Promise
    return axios.get(url3)
      .then((res2) => {
        console.log(res2.data);
        return res2.data;
      });
  });
};

路由部分的代码不需要做任何修改,修改完成后就能正常拿到返回的数组结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 21:18:02