Handling multiple promises in JavaScript can be a bit tricky. π€ Whether you're managing multiple asynchronous operations or just looking to optimize your code, knowing the difference between Promise.all()
and Promise.allSettled()
is crucial. Letβs break down their differences, use cases, and how to use each one effectively.
Promise.all()
π
-
Purpose:
Promise.all()
waits for all promises to resolve. If any promise rejects, it immediately rejects with the reason from the first rejected promise. - Best For: Use this when you need all promises to be successful for the overall operation to be considered successful.
- Example:
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = new Promise((_, reject) => setTimeout(() => reject('Error'), 1000));
Promise.all([p1, p2, p3])
.then(results => console.log('All promises resolved:', results))
.catch(error => console.error('One of the promises failed:', error));
Output: One of the promises failed: Error
(because p3
rejects)
Use Case: Ideal for situations where the failure of any promise means the entire task cannot proceed, such as dependent API requests.
Promise.allSettled()
β
-
Purpose:
Promise.allSettled()
waits for all promises to settle (either resolve or reject) and provides a detailed result for each. - Best For: Use this when you want to handle each promise's result individually, even if some promises fail.
- Example:
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = new Promise((_, reject) => setTimeout(() => reject('Error'), 1000));
Promise.allSettled([p1, p2, p3])
.then(results => {
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Promise ${index + 1} resolved with value: ${result.value}`);
} else {
console.error(`Promise ${index + 1} rejected with reason: ${result.reason}`);
}
});
});
Output:
Promise 1 resolved with value: 1
Promise 2 resolved with value: 2
Promise 3 rejected with reason: Error
Use Case: Useful when you need to know the outcome of all promises, regardless of success or failure, such as running multiple independent tasks.
Key Differences
-
Behavior on Rejection:
-
Promise.all()
: Rejects immediately on the first promise rejection. -
Promise.allSettled()
: Waits for all promises to settle and returns detailed results.
-
-
Result Handling:
-
Promise.all()
: Returns an array of resolved values if successful. -
Promise.allSettled()
: Returns an array of objects withstatus
,value
, orreason
.
-
When to Use Which?
-
Promise.all()
: Ideal for operations where all promises must succeed for the process to proceed. -
Promise.allSettled()
: Best when you need results from all promises, regardless of their outcome.
Understanding these methods will help you manage asynchronous operations more effectively in your JavaScript projects. π
Feel free to share your experiences or ask questions in the comments below!
Top comments (0)