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

0

437
Views
Vue: espere a que el bucle obtenga todos los elementos de forma asíncrona

tengo una matriz de datos para obtener, por lo que tengo que usar un bucle for para obtener todos los datos, pero quiero hacerlo de forma asíncrona (múltiples llamadas al mismo tiempo). Después de haber obtenido los datos, también quiero manipularlos, por lo que necesito ejecutar el código DESPUÉS de que se hayan obtenido todos los datos.

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

El problema es que cada vez que llego a la función manipularData, fetchedData está vacío.

También intenté hacerlo de forma sincrónica usando await y funciona, pero se vuelve muy lento cuando se realizan varias llamadas.

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

0

Puede lograr esto con el método 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) })
over 3 years ago · Juan Pablo Isaza Report

0

Puedes usar 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();
over 3 years ago · Juan Pablo Isaza Report

0

El mejor enfoque que se me ocurre es usar Promise.all() . .then el .then -handler, porque axios.get() le devuelve una promesa.

Puede encontrar un ejemplo de implementación exacto aquí en StackOverflow: Promise All with Axios .

over 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

Show me some job opportunities
There's an error!