0

I need to push all the results into an array making async http calls but i need to wait until all of the calls are finished.

async function(){
  const arrayWithResults = [];
  const urls = ['someurl.com', 'otherurl.com'];
  urls.map( url => {
    axios.get(url).then( result => {
      arrayWithResults.push(result);
    }
  });
}

Is using await the only option here? i'm afraid of using it since awaiting for each request would slow down the whole process.

Enzo Beltrami
  • 81
  • 1
  • 12
  • But potentially better answers here: https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – Herohtar May 09 '18 at 21:08

1 Answers1

2

await the return value of Promise.all instead:

const arrayWithResults = await Promise.all(
  urls.map(url => axios.get(url))
);

Promise.all returns a promise that resolves as soon as all promises passed to it are resolved.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143