Using Promise.all to batch process api calls

javascript

In the following scenario, imagine we need to query a long running function or an endpoint using async/await.

Without Promise.all each of our api calls will be processed individually.

In the below case, the program would wait say 3 seconds (sample latency of 500 ms for every callAPI request). This happens because the await call happened inside the loop. While ok for a small number of calls, we can see how it would cause problems if we have a large dataArray.

const myFunc = async () => {
  for (const data of dataArray) {
    const output = await callAPI(food)
  }
}
run()

We need a way to do all the await calls in parallel instead of waiting for each one to finish before starting the next one.

Promise.all allows up to improve time performance by making multiple calls together
const myFunc = async () => {
  const promises = []

  dataArray.forEach(data => {
    promises.push(callAPI(data))
  })

  const responses = await Promise.all(promises) // all promises resolved in parallel

  responses.forEach(result => console.log(response)) // print responses of all calls
}

Hi, I'm Tom

I’m a Software Developer and Engineering Advocate current working for Deloitte Digital in Ireland. If you are one of the lucky ones to land here, please sign my Guestbook.