Course contentsShow
← JavaScript
Lesson 1304 of 2,72329. PromisesFree lesson

Promise.race Use Cases

Explore practical scenarios like timeout patterns and racing alternative data sources with Promise.race.

Promise.race Use Cases

You'll learn practical patterns where racing promises against each other solves real problems.

The Core Idea

Promise.race settles as soon as any promise finishes — whether it resolves or rejects. This "first past the post" behavior is perfect for two common scenarios: enforcing timeouts and racing redundant data sources.

Timeout Pattern

One of the most valuable uses is preventing slow operations from hanging indefinitely:

function timeout(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(() => reject(new Error('Operation timed out')), ms);
  });
}

function fetchData() {
  // Simulates a potentially slow network request
  return new Promise(resolve => {
    setTimeout(() => resolve('Data arrived'), 5000);
  });
}

Promise.race([
  fetchData(),
  timeout(2000)
])
.then(result => console.log(result))
.catch(err => console.error(err.message)); // "Operation timed out"

If fetchData() takes longer than 2 seconds, the timeout promise rejects first, and your .catch() handler fires. You've effectively added a deadline.

Racing Alternative Sources

When you have multiple servers or APIs that provide the same data, race them to use whichever responds fastest:

function fetchFromServerA() {
  return new Promise(resolve => setTimeout(() => resolve('Data from A'), 300));
}

function fetchFromServerB() {
  return new Promise(resolve => setTimeout(() => resolve('Data from B'), 100));
}

Promise.race([fetchFromServerA(), fetchFromServerB()])
  .then(result => console.log(result)); // "Data from B" (faster)

This improves perceived performance — your user gets results from the quickest source.

Key Takeaway: Use Promise.race to implement timeout patterns that prevent operations from hanging indefinitely, or to compete redundant data sources and use whichever finishes first.