Axios.get().then() 在 for 循环中

新手上路,请多包涵

我将如何在 for 循环中运行 Axios,每个循环都有相应的 .then() 函数。然后for循环结束后,运行另一个函数。

例子:

 const array = ['asdf', 'foo', 'bar'];
let users = [];
for (i = 0; i < array.length; i++) {
  axios.get('/user/' + array[i].id).then(response => {
    // do something with response
    users.push(response);
  });
}

console.log(users);

原文由 user1661677 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 623
2 个回答
const array = [{ id: 'asdf'}, { id: 'foo' }, { id: 'bar' }]; // changed the input array a bit so that the `array[i].id` would actually work - obviously the asker's true array is more than some contrived strings
let users = [];
let promises = [];
for (i = 0; i < array.length; i++) {
  promises.push(
    axios.get('/user/' + array[i].id).then(response => {
      // do something with response
      users.push(response);
    })
  )
}

Promise.all(promises).then(() => console.log(users));

Promise本身的 .then() 方法返回一个Promise;因此您可以收集这些并使用 Promise.all() 等待所有这些。

请注意,即使您在 async 函数中执行此操作,您也不希望 await 在 for 循环中,因为这样每个请求都会等待前一个请求甚至在它开始之前就完成了,大概你想并行运行这些请求。

根据您的用例,简洁的 async / await 函数可能如下所示:

 async function getMultiple(...objectsToGet) {
  let users = [];
  await Promise.all(objectsToGet.map(obj =>
    axios.get('/user/' + obj.id).then(response => {
      // do something with response
      users.push(response);
    })
  ));
  return users;
}

// some other async context
console.log(await getMultiple({ id: 'asdf'}, { id: 'foo' }, { id: 'bar' }));

原文由 Daniel Smedema 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您使用的是支持 async/await 的更新版本的 javascript,您可以执行以下操作:

 const array = ['asdf', 'foo', 'bar'];
let users = [];
for (const id in array) {
  const response = await axios('/user/' + id);
  users.push(response);
}

console.log(users);

原文由 jakemingolla 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题