使用axios进行for循环,我怎么知道是否所有数据都已加载

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。我想知道如何知道循环中的所有数据都已完全加载


天涯尽头无女友
浏览 125回答 2
2回答

守候你守候我

您可以为此使用Promise.all:this.allMyFacilities = response[1].dataconst promises = this.allMyFacilities.map((myFacility) => {&nbsp; &nbsp; return axios&nbsp; &nbsp; &nbsp; &nbsp; .get(facilityUsed(myFacility.id))&nbsp; &nbsp; &nbsp; &nbsp; .then((response) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.facilitiesOnSupplyChain[myFacility.id] = response.data&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return response.data;&nbsp; &nbsp; &nbsp; &nbsp; }).catch((err) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // An error will also be thrown if you use cancel.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.error(err)&nbsp; &nbsp; &nbsp; &nbsp; });});Promise.all(promises).then((allResponsesArray) => /* do sth */)

宝慕林4294392

假设所有异步调用都可以独立进行,您可以利用该Promise.all功能来实现这一点。this.allMyFacilities = response[1].dataawait Promise.all(this.allMyFacilities.map(myFacility) => {&nbsp; return axios.get(facilityUsed(myFacility.id))&nbsp; &nbsp; .then(data => this.facilitiesOnSupplyChain[myFacility.id] =&nbsp; data);});这将允许您axios并行执行所有调用,从而减少整个过程的总体执行时间。PS:我已经写了一个await声明,假设你将把这个功能包装在一个async函数中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript