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.
Promise.race and Promise.allSettled in 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.
Promise.race([promise1, promise2, promise3])
Promise.allSettled([promise1, promise2, promise3])
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.
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); }); });
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.
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.