CodeBlanks Logo Icon CodeBlanks

Promise.all and Promise.race

JavaScript course · Intermediate · Lesson 76/134

Learn Promise.all for parallel promises and Promise.race.

Parallel work with Promise.all

Promise.all takes an array of promises and returns one promise that fulfils when all of them fulfil. The results arrive in the same order as the input array. If any promise in the array rejects, Promise.all rejects immediately and does not wait for the rest.

Promise.all([loadUser(), loadPosts()])
  .then(results => console.log(results));

This method is ideal for running independent jobs in parallel. Use it when all of them must succeed.

Racing with Promise.race

Promise.race also takes an array, but it settles with the first promise that settles. If the first one fulfils, the result fulfils; if it rejects, the result rejects. The rest are ignored.

Promise.race([fetchWithTimeout(), slowFetch()])
  .then(result => console.log(result));

This method is handy for implementing a timeout pattern. The fastest response wins, so the user does not wait.

Exercise Parallel loading with Promise.all

Two functions called loadProfile and loadStats each return a promise. Run both in parallel with Promise.all. In then receive the results array as the results parameter and log it with console.log. Add catch at the end of the chain and log the error.

Show example solution
Promise.all([loadProfile(), loadStats()])
  .then(results => console.log(results))
  .catch(error => console.log(error));

Test yourself

  1. When does Promise.all reject?

    • Never
    • When any promise in the array rejects
    • When all promises fulfil
    • Only when the first promise rejects
    Show answer

    When any promise in the array rejects — Correct! Promise.all rejects as soon as any promise in the array rejects.

  2. Promise.all call

    Promise.____([loadUser(), loadPosts()])
      .then(results => console.log(results));
    Show answer
    Promise.all([loadUser(), loadPosts()])
      .then(results => console.log(results));
  3. Promise.all and Promise.race

    Promise.all
    Result when all fulfil
    Promise.race
    Returns the first to settle
    parallel
    Run independent jobs at once

All lessons in Intermediate