对于带有 axios 的循环,我怎么知道是否加载了所有数据


this.allMyFacilities = response[1].data
for (let i = 0; i < this.allMyFacilities.length; i++) {
axios
.get(facilityUsed(this.allMyFacilities[i].id))
.then((response) => {
this.facilitiesOnSupplyChain[this.allMyFacilities[i].id] = response.data
})
.catch((err) => {
// An error will also be thrown if you use cancel.
console.error(err)
})
}

我有这样的代码。我不知道我有多少设施。那是我循环它,但是每个设施都有自己的Axios。我想如何知道循环中的所有数据都已完全加载

你可以使用 Promise.all 来实现这一点:

this.allMyFacilities = response[1].data
const promises = this.allMyFacilities.map((myFacility) => {
return axios
.get(facilityUsed(myFacility.id))
.then((response) => {
this.facilitiesOnSupplyChain[myFacility.id] = response.data
return response.data;
}).catch((err) => {
// An error will also be thrown if you use cancel.
console.error(err)
});
});
Promise.all(promises).then((allResponsesArray) => /* do sth */)

假设所有异步调用都可以独立进行,则可以利用Promise.all功能来实现此目的。

this.allMyFacilities = response[1].data
await Promise.all(this.allMyFacilities.map(myFacility) => {
return axios.get(facilityUsed(myFacility.id))
.then(data => this.facilitiesOnSupplyChain[myFacility.id] =  data);
});

这将允许您并行执行所有axios调用,从而减少整个过程的整体执行时间。

附注: 我已经写了一个await语句hance,假设您将此功能包装在async函数中。

最新更新