You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Node.js中使用Axios在For循环中等待GET请求完成的问题

解决异步请求未完成就返回结果的问题

你的核心问题是没有等待所有异步的axios请求完成就返回了results数组。axios.get是异步操作,循环里只是快速发起了所有请求,但这些请求的响应还没回来,你的函数就已经执行到return results语句了,所以打印出来是空数组。

下面给你两种可行的解决方案:

方案1:使用await逐个等待请求完成(顺序执行)

这种方式会按顺序发起请求,前一个请求完成后再发起下一个,适合需要保证请求顺序的场景:

const axios = require("axios");
// 注意:数组元素要加引号,否则会被当作未定义的变量
const loop = ["about", "home", "products", "thanks"];
const test = async () => {
  const results = [];
  // 用let声明i,避免全局作用域污染
  for (let i = 0; i < loop.length; i++) {
    try {
      // 用await等待请求完成,再把结果push到数组
      const response = await axios.get(`https://examplewebsite.com/${loop[i]}`);
      results.push(response);
    } catch (error) {
      console.log(`请求${loop[i]}时出错:`, error);
    }
  }
  // 现在所有请求都完成了,再返回结果
  return results;
};

test().then((results) => {
  console.log(results); // 会输出所有请求的响应结果
});

方案2:使用Promise.all并行处理所有请求(效率更高)

如果不需要保证请求的顺序,这种方式会同时发起所有请求,等待全部完成后一次性获取结果,效率比顺序执行高:

const axios = require("axios");
const loop = ["about", "home", "products", "thanks"];
const test = async () => {
  // 先把每个请求转换成Promise对象,组成数组
  const requestPromises = loop.map(async (path) => {
    try {
      return await axios.get(`https://examplewebsite.com/${path}`);
    } catch (error) {
      console.log(`请求${path}时出错:`, error);
      // 可以返回null或者自定义错误对象,避免Promise.all因为一个失败就全部失败
      return null;
    }
  });

  // 等待所有Promise完成,得到结果数组
  const results = await Promise.all(requestPromises);
  // 过滤掉null的结果(如果有请求失败的话)
  return results.filter(result => result !== null);
};

test().then((results) => {
  console.log(results); // 输出所有成功请求的响应结果
});

额外注意点:

  • 原代码里的loop数组元素没有加引号,会被当作未定义的变量,一定要修正为字符串数组。
  • 尽量避免使用var声明变量(比如原代码里的var i),改用letconst,避免作用域问题。

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

火山引擎 最新活动