0
0
Node.jsframework~5 mins

Promise.race and Promise.allSettled in Node.js

Choose your learning style9 modes available
Introduction

Promise.race and Promise.allSettled help you handle multiple tasks that happen at the same time. They let you decide what to do when some or all tasks finish.

You want to get the result of the fastest task among many.
You want to wait for all tasks to finish, no matter if they succeed or fail.
You want to handle multiple requests and see which one finishes first.
You want to know the outcome of every task without stopping on errors.
You want to run several tasks and continue only after all have settled.
Syntax
Node.js
Promise.race(iterableOfPromises)
Promise.allSettled(iterableOfPromises)

Promise.race returns a promise that settles as soon as one of the promises settles (either fulfilled or rejected).

Promise.allSettled returns a promise that resolves after all promises have settled, with an array of their results.

Examples
Returns the result of the first promise that finishes, whether it succeeds or fails.
Node.js
Promise.race([promise1, promise2, promise3])
Waits for all promises to finish and gives you an array showing which succeeded or failed.
Node.js
Promise.allSettled([promise1, promise2, promise3])
Sample Program

This code creates three promises: one resolves after 300ms, one rejects after 200ms, and one resolves after 400ms.

Promise.race returns the first promise that settles, which is the rejected one after 200ms.

Promise.allSettled waits for all promises to finish and then shows their status and values or reasons.

Node.js
const promise1 = new Promise(resolve => setTimeout(() => resolve('First done'), 300));
const promise2 = new Promise((_, reject) => setTimeout(() => reject('Second failed'), 200));
const promise3 = new Promise(resolve => setTimeout(() => resolve('Third done'), 400));

// Using Promise.race
Promise.race([promise1, promise2, promise3])
  .then(result => console.log('Race result:', result))
  .catch(error => console.log('Race error:', error));

// Using Promise.allSettled
Promise.allSettled([promise1, promise2, promise3])
  .then(results => {
    console.log('AllSettled results:');
    results.forEach((res, i) => {
      console.log(`Promise ${i + 1}:`, res.status, res.status === 'fulfilled' ? res.value : res.reason);
    });
  });
OutputSuccess
Important Notes

Promise.race settles as soon as any promise settles, so it can reject or resolve first.

Promise.allSettled never rejects; it always resolves with the status of all promises.

Use Promise.allSettled when you want to know the outcome of all promises without stopping on errors.

Summary

Promise.race gives you the first finished promise result or error.

Promise.allSettled waits for all promises and tells you how each ended.

Both help manage multiple tasks running at the same time in a simple way.