Promise.all with async/await in JavaScript

Promise.all can be used to await an array of promises, all of which can resolve at any time individually. Imagine launching multiple simultaneous requests to many APIs for example, all with varying unpredictable response times.

Promise.all will only resolve once all of the promises in the input array have resolved.

The following example shows two functions which return in 1 and 2 seconds respectively. Note that we are using the sleep function from npm here for maximum simplicity. This can be installed with: npm install sleep.

const sleep = require('sleep')

const f = async () => {
  sleep.sleep(1) // 1 second
  console.log('f sleep done, returning...')
  return 'f result'
}

const g = async () => {
  sleep.sleep(2) // 2 seconds
  console.log('g sleep done, returning...')
  return 'g result'
}

(async () => {
  const promise1 = f()
  const promise2 = g()

  const allResults = await Promise.all( [promise1, promise2] )

  console.log('All results: ' + JSON.stringify(allResults))
})()

Note the IIFE because we cannot have a top-level async function using the async/await syntax.

If we don’t need the return values, we can simply do:

await Promise.all( [promise1, promise2] )

To capture only some of the results, we can use destructuring assignment:

const [ result1 ] = await Promise.all( [promise1, promise2] )

The combination of Promise.all and async/await provides a very readable and compact way to make many asynchronous calls and use the results.

 

Leave a Reply

Your email address will not be published. Required fields are marked *