Promise.all & Promise.race

Both Promise.all and Promise.race are methods to handle multiple promises concurrently in JavaScript. They allow you to coordinate asynchronous operations efficiently.

Comparison: Promise.all vs Promise.race
FeaturePromise.allPromise.race
PurposeWaits for all promises to fulfillWaits for the first promise to settle (fulfill or reject)
ReturnsAn array of all resultsThe result of the first settled promise
Reject behaviorRejects immediately if any promise rejectsResolves or rejects as soon as one promise settles
Use caseWhen all results are needed before proceedingWhen you want the fastest result among many
Illustration of promise_all_race
Illustration of promise_all_race

💡 Key Concept

Promise.all aggregates multiple promises and fails fast if any reject, while Promise.race settles as soon as any promise settles, regardless of success or failure.

How to use Promise.all

Pass an iterable of promises. It fulfills when all promises fulfill, returning an array of their results in the same order.

📌 Deep Dive: Promise.all Example

JAVASCRIPT
Promise.all([
  Promise.resolve(1),
  Promise.resolve(2),
  Promise.resolve(3)
]).then(results => {
  console.log(results);
});
Output
[1, 2, 3]

How to use Promise.race

Pass an iterable of promises. It settles as soon as the first promise settles (fulfills or rejects) and returns that result or error.

📌 Deep Dive: Promise.race Example

JAVASCRIPT
Promise.race([
  new Promise(resolve => setTimeout(() => resolve('First'), 100)),
  new Promise(resolve => setTimeout(() => resolve('Second'), 200))
]).then(result => {
  console.log(result);
});
Output
First

⚠️ Important

If any promise passed to Promise.all rejects, the entire Promise.all rejects immediately with that reason. In contrast, Promise.race resolves or rejects as soon as the first promise settles, without waiting for others.

Practical Use Cases

  • Promise.all: Fetching multiple API endpoints simultaneously and waiting for all responses.
  • Promise.race: Implementing a timeout for a network request by racing the fetch promise with a timeout promise.

📌 Deep Dive: Using Promise.race for Timeout

JAVASCRIPT
const fetchData = fetch('https://api.example.com/data');
const timeout = new Promise((_, reject) => 
  setTimeout(() => reject(new Error('Timeout')), 5000)
);

Promise.race([fetchData, timeout])
  .then(response => console.log('Data fetched', response))
  .catch(error => console.error(error));
Output
(Data fetched or Timeout error after 5 seconds)

💡 Summary

Promise.all waits for all promises to complete and aggregates their results, rejecting if any fail. Promise.race settles as soon as the first promise settles, useful for timeouts or fastest response selection.