Managing multiple asynchronous operations in JavaScript can become complex. Fortunately, JavaScript provides several built-in methods—.all(), .allSettled(), .race(), and .any()—to handle such operations gracefully. This blog provides a professional, structured comparison of these promise methods with real code examples and practical use cases.
Understanding the Basics
Before diving into comparisons, let’s revisit what a Promise is:
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
Each of the methods we’ll discuss below operates on an array of promises and provides different behaviors based on their resolution or rejection.
Promise.all() – Wait for All to Succeed
Promise.all() returns a single promise that resolves when all of the input promises resolve, or rejects if any of the promises reject.
Use Case
Use when all tasks are required to succeed. If even one fails, the entire operation fails.
Example
const p1 = Promise.resolve('Result 1');
const p2 = Promise.resolve('Result 2');
const p3 = Promise.reject('Error in p3');
Promise.all([p1, p2, p3])
.then(results => console.log('All success:', results))
.catch(error => console.error('At least one failed:', error));
Output
At least one failed: Error in p3
Promise.allSettled() – Wait for All to Finish (Regardless of Success or Failure)
Returns a promise that resolves after all promises have settled (fulfilled or rejected). It never rejects.
Use Case
Promise.allSettled([p1, p2, p3])
.then(results => console.log('All settled:', results));
Output
[
{ status: 'fulfilled', value: 'Result 1' },
{ status: 'fulfilled', value: 'Result 2' },
{ status: 'rejected', reason: 'Error in p3' }
]
Promise.race() – First Settled Wins
Returns a promise that settles as soon as the first promise settles (either resolved or rejected).
Use Case
Use when you care about the fastest result, regardless of outcome.
Example
const fast = new Promise(resolve => setTimeout(() => resolve("Fast!"), 100));
const slow = new Promise(resolve => setTimeout(() => resolve("Slow!"), 500));
Promise.race([fast, slow])
.then(result => console.log('Winner:', result));
Output
Winner: Fast!
Promise.any() – First Successful Only
Returns a promise that fulfills as soon as any of the input promises fulfills. Rejects only if all of them reject.
Use Case
Use when you want at least one success, and can ignore failures
Example
const fail1 = Promise.reject("Fail 1");
const fail2 = Promise.reject("Fail 2");
const success = Promise.resolve("Success!");
Promise.any([fail1, fail2, success])
.then(result => console.log("First success:", result))
.catch(err => console.log("All failed", err));
Output
First success: Success!
Summary
- Use Promise.all() when everything must succeed.
- Use Promise.allSettled() to inspect all outcomes.
- Use Promise.race() for the fastest result (good or bad).
- Use Promise.any() to get the first successful result only.