• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

389
Views
Vue - Wait for for loop to fetch all items asynchronously

i have an array of data to be fetched, so i have to use a for loop to fetch all the data, but i want to do it asynchronously (multiple calls at the same time). After having fetched the data i also want to do some data manipulation, so i need to run code AFTER all the data has been fetched

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

The problem is that whenever i reach the manipulateData function, fetchedData is empty.

Also i tried doing it synchronously using await and it works but it becomes very slow when making multiple calls.

about 3 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can achieve this with Promise.all-method.

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)
})
about 3 years ago · Juan Pablo Isaza Report

0

You can use 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();
about 3 years ago · Juan Pablo Isaza Report

0

The best approach I can think of is to use Promise.all(). You will leave out the .then-handler, because axios.get() returns you a promise.

An exact implementation example can be found here at StackOverflow: Promise All with Axios.

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error