Elias
Elias

Reputation: 199

for loop with axios, how do I know if all data are loaded

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)
              })
          }

I have such a code. I don't know how many facilities do I have. that is I loop it, But each facility has its own Axios. I want to how do I know all data from the loop are completely loaded

Upvotes: 1

Views: 644

Answers (2)

Dhruv Shah
Dhruv Shah

Reputation: 1651

Assuming that all the asynchronous calls can be made independently, you can leverage upon the Promise.all functionality to achieve this.

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);
});

This will allow you to execute all the axios calls in parallel, and hence decrease the overall execution time of the whole process.

PS: I have written an await statement hance assuming that you will be wrapping this functionality in an async function.

Upvotes: 1

Benjamin Eckardt
Benjamin Eckardt

Reputation: 728

You can use Promise.all for this:

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 */)

Upvotes: 2

Related Questions