【问题标题】:Send multiple axios requests in a for loop in series (One after the other)在for循环中串行发送多个axios请求(一个接一个)
【发布时间】:2020-11-16 08:06:57
【问题描述】:

目前我正在使用 Promise.all() 一次发送多个 axios 请求,但我想一个一个发送请求,这意味着在第一个请求完成后发送第二个请求。

这很重要,因为 POST 请求的时间戳很重要。对数组第 0 个元素中的 promise 的 POST 请求需要具有比第 1 个元素中的 promise 更早的时间戳,依此类推。

这是我目前写的代码。

Promise.all(
  rowNodes.map((row) => {
    axios.post(url, row, axiosOptions);
  })
)
  .then((responseArr) => {
    console.log(responseArr);
  })
  .catch((errorArr) => {
    console.log(errorArr);
  });

【问题讨论】:

标签: javascript reactjs axios


【解决方案1】:

请尝试在async/await 函数中使用for 循环。如下所示

const someFunc = async () => {
  ...
  const responses = [];
  for (let i = 0; i < rowNodes.length; i++) {
    responses.push(await axios.post(url, rowNodes[i], axiosOptions));
  }
  ...
}

【讨论】:

  • @dracarys 你将循环包裹在 try/catch 块中
  • 对于结果,你可以将每个结果推送到一个数组中。以results.push(await axios.post()); 为例。
猜你喜欢
  • 1970-01-01
  • 2020-10-19
  • 2020-01-01
  • 2011-07-01
  • 2022-07-21
  • 1970-01-01
  • 2021-12-26
  • 2018-11-05
  • 2022-11-02
相关资源
最近更新 更多