Vue - 等待循环异步获取所有项目

Vue - Wait for for loop to fetch all items asynchronously

我有一个数据数组要获取,所以我必须使用for循环来获取所有数据,但我想异步执行(同时调用多个)。 获取数据后我还想进行一些数据操作,所以我需要 运行 在获取所有数据后编写代码

for (var e in this.dataTofetch) {
  axios
    .get("https://www.example.com/api/" + e)
    .then((response) => this.fetchedData.push(response.data));
}
this.manipulateData();

问题是每当我到达 manipulateData 函数时,fetchedData 是空的。

我也尝试使用 await 同步执行它并且它有效但是在进行多次调用时它变得非常慢。

我能想到的最佳方法是使用 Promise.all()。您将省略 .then-处理程序,因为 axios.get() returns 您是一个承诺。

可在 Whosebug 此处找到准确的实施示例:

您可以使用 Promise.all 方法实现此目的。

const promises = this.dataTofetch.map(e =>axios
    .get("https://www.example.com/api/" + e))
Promise.all(promises).then(arrOfRes => {
    // Do something with the responses (arrOfRes[x] = response)
})

您可以使用Promise.all()

Promise.all(
  this.dataTofetch.map(e => axios.get(`https://www.example.com/api/${e}`)),
).then(responses =>
  responses.forEach(r => this.fetchedData.push(r.data)),
);

this.manipulateData();