Handle multiple async data simultaneously in Javascript using promise.all

Ever been in a situation where you want to use data from multiple async functions/APIs. The first inclination is usually to create nested then callbacks, but this can be ambiguous and also take some extra time since it will run sequentially. A great alternative is promise.all which can run multiple promises concurrently(aka “in parallel”), waiting for all of them to complete before proceeding.

For example we have the following async functions each of which returning different numbers after certain periods of time.

/*** Just a function to return 20 after 3 seconds ***/
const promiseTwenty = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(20)
    }, 3000)
  }
}
/*** Just a function to return 30 after 5 seconds ***/
const promiseThirty = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(30)
    }, 5000)
  }
}

So we’ll declare a function to add the returned values from both async functions. Arguments to this function will be the promises.

Note: Promise.all() takes only one argument, an array consisting of either promise instances, thenables or even immediate values.

const add = (asyncFunc1, asyncFunc2) => {
  return Promise.all([asyncFunc1, asyncFunc2]).then(values => {
    /*** values is an array ***/
    return values[0] + values[1]
  }
}

values (the argument in the then callback above) is an array of all returned values from the respective async functions in order regardless of their completion times. Let’s now invoke our function to add return values of promiseThirty and promiseTwenty.

add(promiseTwenty(), promiseThirty()).then(
  result => {
    /*** result is 50 ***/
    console.log(result)
  },
  error => {
     /*** Incase of an error ***/
    console.log(error)
  })

There we go handling multiple async data using promise.all