【问题标题】:Axios.get().then() in a for loopfor 循环中的 axios.get().then()
【发布时间】:2019-10-25 05:22:13
【问题描述】:

我将如何在 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);

【问题讨论】:

  • 你可以使用await关键字
  • Promise.all(users.map(u =&gt; axios.get(`/user/${u.id}`))).then(console.log, console.error) 将返回日志每个结果的数组。输出的顺序将与原始输入的顺序相匹配。

标签: javascript promise axios


【解决方案1】:

你应该在一个数组中收集所有的 Promise 并按以下方式使用 promise.all -

const array = ['asdf', 'foo', 'bar'];
let promises = [];
for (i = 0; i < array.length; i++) {
  promises.push(axios.get('/user/' + array[i].id))
}

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

【讨论】:

  • 如果您不希望自己的回答混淆,会发生什么?每个响应都将其各自的结果分别放在一个数组中?
【解决方案2】:

如果您使用支持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);

【讨论】:

  • 谢谢,这成功了。但是,在for...in 循环中,id 指向索引而不是值。所以在这里你需要array[id] 来访问这些元素。否则你可以使用for..of循环。
【解决方案3】:
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 函数中执行此操作,您也不希望在 for 循环中使用 await,因为这样每个请求都将等待前一个请求完成,然后才开始,并且大概您希望并行运行这些请求。

根据您的用例,简洁的 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' }));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2021-07-30
    相关资源
    最近更新 更多