Promise Combinators in JavaScript
Promise combinators are special methods that allow you to handle multiple promises simultaneously. They help manage asynchronous operations in bulk and provide different ways to react depending on how the promises settle.
Promise.all(iterable)
- Waits for all Promises in an iterable (array) to resolve.
- If any promise rejects, it immediately rejects with that reason.
- Returns a single promise that resolves to an array of results.
- Use case: When you need all tasks to complete successfully before proceeding.
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = Promise.resolve(3);
Promise.all([p1, p2, p3]).then(results => console.log(results));
// Output: [1, 2, 3]
Promise.race(iterable)
- Resolves or rejects as soon as any promise in the iterable settles (first to finish).
- Returns a promise that adopts the state and value/reason of the first settled promise.
- Use case: When you want the fastest response among multiple async tasks.
const p1 = new Promise(res => setTimeout(res, 100, "One"));
const p2 = new Promise(res => setTimeout(res, 50, "Two"));
Promise.race([p1, p2]).then(result => console.log(result));
// Output: "Two"
Promise.any(iterable) (ES2021+)
- Waits for the first promise to fulfill.
- Ignores rejected promises until at least one fulfills.
- If all promises reject, it rejects with an AggregateError.
- Use case: When you only care about the first successful result, not failures.
const p1 = Promise.reject("Error 1");
const p2 = Promise.resolve("Success");
const p3 = Promise.reject("Error 2");
Promise.any([p1, p2, p3]).then(result => console.log(result));
// Output: "Success"
Summary Table:
Combinator | Behavior | Rejects If |
---|---|---|
Promise.all | Waits for all promises to fulfill | Any promise rejects |
Promise.race | Settles as soon as first promise settles | First settled promise rejects |
Promise.any | Waits for first fulfilled promise | All promises reject |