Promise.all, allSettled, race & any
Four ways to combine promises -- pick the one whose failure and timing semantics match your goal.
Syntax
await Promise.all([...])
await Promise.allSettled([...])
await Promise.race([...])
await Promise.any([...])Running several promises together is common; choosing the right combinator is what separates robust code from flaky code.
| Combinator | Resolves when | Rejects when |
|---|---|---|
all | every promise fulfils | the first one rejects (fail-fast) |
allSettled | every promise settles | never -- you get status objects |
race | the first settles (either way) | if that first one rejects |
any | the first fulfils | only if all reject (AggregateError) |
Choosing
- All results required, any failure is fatal ->
all. - Want every outcome regardless of failures (dashboards, batch jobs) ->
allSettled. - First to finish wins, e.g. a timeout ->
race. - First success wins, tolerate failures (mirror servers) ->
any.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Load a dashboard by running profile, orders, and recommendations in parallel with Promise.all.
- Implement a primary/fallback fetch strategy using Promise.any where the first responder wins.
- Audit which of several microservices are down by using Promise.allSettled to collect all statuses.
More examples
Promise.all for parallel success
Runs two fetches in parallel and resolves once both succeed; rejects immediately if either fails.
const [user, posts] = await Promise.all([
fetch("/api/user").then(r => r.json()),
fetch("/api/posts").then(r => r.json())
]);
console.log(user.name, posts.length);Promise.any for first success
Promise.any resolves with the first successful result, making it ideal for redundant CDN failover.
const fastest = await Promise.any([
fetch("https://cdn1.example.com/data").then(r => r.json()),
fetch("https://cdn2.example.com/data").then(r => r.json())
]);
console.log("Got data from fastest CDN:", fastest);Promise.allSettled for status audit
Checks all service health endpoints in parallel and reports each as UP or DOWN regardless of failures.
const services = ["/health/auth", "/health/db", "/health/cache"];
const results = await Promise.allSettled(services.map(url => fetch(url)));
results.forEach((r, i) => {
console.log(services[i], r.status === "fulfilled" ? "UP" : "DOWN");
});
Discussion