CodeBlanks Logo Icon CodeBlanks

Promise.race

Learn to await the first to finish with Promise.race.

What is Promise.race?

Promise.race takes an array of Promises and returns the result of the first one to settle (fulfilled or rejected). It works like a race: the first to finish wins and its result becomes the result of the whole race call. The other Promises still run but their results are ignored.

Promise.race([fast, slow])
  .then(winner => console.log(winner));

This method is useful to put a timeout on an operation: you race the main work against a timeout Promise; if the timeout finishes first, you get an error.

The timeout pattern

A common use of Promise.race is to put a timeout on long operations. You race the main work against a timeout Promise that rejects after a fixed delay. If the work finishes before the timeout, race fulfils with its result; if the timeout fires first, race rejects with an error.

function timeout(ms) {
  return new Promise((_, reject) =>
    setTimeout(() => reject(new Error("timeout")), ms)
  );
}

Here timeout(1000) rejects after 1000 ms; racing the main work against it gives an error if the work takes longer than a second.

Practice Your turn: first result with Promise.race

Create two Promises: const fast = new Promise(res => setTimeout(() => res("fast"), 10)) and const slow = new Promise(res => setTimeout(() => res("slow"), 50)). Call Promise.race([fast, slow]) and log the winner with .then(winner => console.log(winner)).

Starter code

index.js
// Create fast and slow Promises
// Use Promise.race to log the winner

Sample solution

index.js
const fast = new Promise(res => setTimeout(() => res("fast"), 10));
const slow = new Promise(res => setTimeout(() => res("slow"), 50));
Promise.race([fast, slow]).then(winner => console.log(winner));

Expected output

fast

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Promise.race concepts

Term Meaning
race first to settle
timeout time limit
winner race winner

2 If the first of two Promises rejects, what does Promise.race return?

  • It waits for the second Promise
  • It returns an empty value
  • It immediately rejects with that error Correct answer
  • It creates a new Promise

Explanation: If the first to settle is a rejection, race rejects too.

3 Fill in the blank: Promise.race

Question
const a = Promise.resolve("a");
const b = Promise.resolve("b");
____([a, b]).then(winner => console.log(winner));
Answer
const a = Promise.resolve("a");
const b = Promise.resolve("b");
Promise.race([a, b]).then(winner => console.log(winner));

Explanation: race returns the first to settle.

All lessons in Beginner