Asynchronous: Orchestrating promises

Promise.all()

If you need to synchronize different promises, Promise.all() helps you define a list of promises, and execute something when they are all resolved.

Promise.all() executes the callback function passed to its then() method when all of the promises you pass to it successfully resolve.

Example:

const f1 = fetch('/something.json')
const f2 = fetch('/something2.json')

Promise.all([f1, f2]).then(([res1, res2]) => {
  console.log('Results', res1, res2)
})

res1 and res2 are objects, each containing the data of the network request response.

Promise.race()

Promise.race() executes the callback function passed to its then() method as soon as one of the promises you pass to it resolves.

It runs the callback function just once, with the result of the first promise resolved.

Example:

const promiseOne = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, 'one')
})
const promiseTwo = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'two')
})

Promise.race([promiseOne, promiseTwo]).then(result => {
  console.log(result) // 'two'
})

Promise.allSettled()

The Promise.allSettled() method is similar to Promise.all() but with one key difference.

Promise.all() executes the callback function passed to its then() method when all of the promises you pass to it resolve.

Promise.allSettled() executes the callback function passed to its then() method when all of the promises you pass to it either resolve OR are rejected.

In the callback function you will have an array of results, each with a set of status and value properties.

Example:

const f1 = fetch('https://api.github.com/users/flaviocopes')
const f2 = fetch('https://api.github.com/users/dhh')

Promise.allSettled([f1, f2]).then(([res1, res2]) => {
  console.log(res1.status, res1.value) // status = 'fulfilled', value = Response object
  console.log(res2.status, res2.value)  // status = 'fulfilled', value = Response object
})

With an invalid URL, like this:

const f1 = fetch('https://api.github.com/users/flaviocopes')
const f2 = fetch('test')

Promise.allSettled([f1, f2]).then(([res1, res2]) => {
  console.log(res1.status, res1.value)
  console.log(res2.status, res2.value)
})

status in the second request will be 'rejected' and the value of the response will be undefined.

Lessons in this unit:

0: Introduction
1: Callbacks
2: Timers
3: Promises
4: Async functions
5: Chaining promises
6: ▶︎ Orchestrating promises
Want to learn more? Check out our courses