Promise Concurrency Combinators: all, any, allSettled
System DesignModel answerLast updated
Compare how Promise.all, Promise.any, and Promise.allSettled settle, handle failures, and order results, then pick the right one for three real service-orchestration scenarios.
Background
You're building a backend-for-frontend (BFF) layer that fires off concurrent requests to several downstream services. JavaScript gives you three built-in combinators for coordinating a group of promises: Promise.all, Promise.any, and Promise.allSettled. Choosing the wrong one leads to silent failures, unnecessarily aborted requests, or stalled responses.
What you need to cover
Part 1 — Behavioral comparison
Walk through how the three combinators differ across these five dimensions:
- Resolution trigger: under what condition does the returned promise fulfill?
- Rejection trigger: under what condition does it reject, and what does the rejection value look like?
- Resolved value shape: what does a successful result actually contain?
- Ordering: do results reflect the input order or the order in which promises settled?
- Empty input: what happens when you pass
[]to each one?
Part 2 — Lifecycle and failure semantics
Address both of the following:
- When
Promise.allshort-circuits on the first rejection, orPromise.anyshort-circuits on the first fulfillment, what happens to the other in-flight promises? Does the runtime cancel the underlying network I/O? - Where do unhandled promise rejection warnings actually come from when working with these combinators, and how do you prevent them?
Part 3 — Scenario matching
For each use case below, name the best combinator and explain why the others would be wrong:
- Widget dashboard: a page loads data for five independent widgets. A single failing widget should show an inline error; the other four must still display their data.
- Payment validation: a purchase requires sign-off from a fraud service, a stock service, and a funds service. If any one of them rejects or returns a denial, the whole transaction must abort as fast as possible.
- Geo-redundant asset fetch: the same config file is served from three CDN regions. You want whichever region responds successfully first; a region that returns an HTTP error should not "win."
Hints
Hint 1
Think about what 'all' and 'any' mean in set logic when the input set is empty — that should tell you exactly what Promise.all([]) and Promise.any([]) return without memorizing the spec.
Hint 2
Short-circuiting means the combinator stops caring about the remaining promises, not that those promises stop running. What would you need to add to actually cancel in-flight fetch requests?
Hint 3
Promise.race and Promise.any look similar for the CDN scenario — think carefully about what each one does when the fastest promise rejects rather than fulfills.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core behavioral differences
All three combinators iterate their input, wrap each item with Promise.resolve, attach internal handlers to every promise, and return a new single promise. The only thing that differs is the rule for when that outer promise settles.
| Dimension | Promise.all | Promise.allSettled | Promise.any |
|---|---|---|---|
| Fulfills when | every input fulfills | every input has settled (either way) | the first input fulfills |
| Rejects when | the first input rejects | never (rejects only for an invalid iterable, with TypeError) | every input rejects |
| Rejection value | that first rejection reason | — | AggregateError; .errors holds all reasons in input order |
| Resolved shape | [v0, v1, …] in input order | [{status, value/reason}, …] in input order | a single value |
| Result ordering | input order, not completion order | input order, not completion order | n/a — single value |
Promise.all([]) | fulfills immediately with [] | fulfills immediately with [] | rejects immediately with AggregateError({ errors: [] }) |
The empty-array behavior follows directly from the semantics. "Every one of zero promises fulfilled" is vacuously true, so all and allSettled resolve right away. "At least one of zero promises fulfilled" is false, so any rejects. These promises settle synchronously in the same microtask tick, though your .then/.catch callbacks still run asynchronously as microtasks. Promise.race([]), by contrast, stays pending forever because its rule ("the first one to settle") can never trigger.
Short-circuiting is not cancellation
When Promise.all rejects early, or Promise.any fulfills early, the combinator simply stops listening to the other promises. It does not cancel them:
fetchcalls keep running.- TCP connections remain open.
- Server-side work continues.
- Any side effects — writes, charges, sends — still happen.
A promise represents a result, not a running task, and the spec has no cancellation primitive built in. To actually stop in-flight requests you need an AbortController and must call ctrl.abort() yourself, typically in a catch or finally block.
Unhandled rejection warnings
Because each combinator attaches a rejection handler to every input promise immediately, a late rejection on one of the inputs is already "handled" by the combinator's internal machinery — no unhandled rejection event fires. The real traps are:
- Eager promise creation, sequential await. If you do
const a = fetchA(); const b = fetchB(); await a;andbrejects while you're still awaitinga,bhas no handler yet. Fix: hand both promises to a combinator before anyawait. - Forgetting to handle the combinator's own returned promise. The combinator itself can reject; leaving that unhandled is the same problem.
- Swallowing all but the first error with
Promise.all. If you need every failure for logging or diagnostics, useallSettledinstead. Promise.anyerrors. If everything fails, theAggregateErroris the rejection reason. Always inspecterr.errors, noterr.message, to see what went wrong per-service.
Scenario selection
Widget dashboard → Promise.allSettled.
The widgets are fully independent, and a partial result is perfectly acceptable. allSettled never rejects, returns one status object per widget at the same index as its input, and makes it trivial to map index i to widget i and render either data or an error state. Promise.all would blank the entire dashboard the moment any single widget fails.
Payment validation → Promise.all.
Every check is mandatory. Rejection of any one check must abort immediately — exactly what all provides. Model a business denial as a thrown rejection, not as a fulfilled { ok: false }, or all won't short-circuit on it. Pair it with AbortController so the other in-flight checks actually stop. On success, all gives you all three responses in a predictable order for destructuring.
Geo-redundant asset fetch → Promise.any.
You want the first successful response. Promise.race would be wrong here: a region that replies quickly with a 500 would win the race before a healthy region finishes. Promise.any ignores rejections and only fulfills when a response is actually good. If every region fails you get an AggregateError listing all three reasons. Abort the losing requests in a finally block.
Reference implementation
// 1. Dashboard — tolerate partial failure
async function loadDashboard(widgetUrls, { timeoutMs = 5000 } = {}) {
const results = await Promise.allSettled(
widgetUrls.map(url =>
fetch(url, { signal: AbortSignal.timeout(timeoutMs) }).then(r => {
if (!r.ok) throw new Error(`${url}: HTTP ${r.status}`);
return r.json();
})
)
);
return results.map((r, i) =>
r.status === 'fulfilled'
? { widget: i, data: r.value }
: { widget: i, error: String(r.reason) }
);
}
// 2. Payment validation — fail fast, cancel the rest
async function validatePayment(tx) {
const ctrl = new AbortController();
const check = url =>
fetch(url, { method: 'POST', body: JSON.stringify(tx), signal: ctrl.signal })
.then(async r => {
const body = await r.json();
if (!r.ok || body.decision !== 'approve') {
throw new Error(`${url} denied: ${body.reason ?? r.status}`);
}
return body;
});
try {
const [fraud, stock, funds] = await Promise.all([
check('/validate/fraud'),
check('/validate/stock'),
check('/validate/funds'),
]);
return { fraud, stock, funds };
} catch (err) {
ctrl.abort(err); // cancel remaining in-flight checks
throw err;
}
}
// 3. CDN fetch — first healthy region wins
async function fetchConfig(mirrors) {
const ctrl = new AbortController();
try {
return await Promise.any(
mirrors.map(url =>
fetch(url, { signal: ctrl.signal }).then(r => {
if (!r.ok) throw new Error(`${url}: HTTP ${r.status}`);
return r.json();
})
)
);
} catch (err) {
if (err instanceof AggregateError) {
throw new Error('All CDN mirrors failed', { cause: err.errors });
}
throw err;
} finally {
ctrl.abort(); // cancels the slower requests once a winner is found
}
}
Complexity and edge cases
Time complexity: O(n) to attach handlers. Wall-clock latency varies:
all— max latency on success; time-to-first-rejection on failure.allSettled— always max latency.any— time to first fulfillment; max latency only if everything fails.
Space complexity: O(n) for the results array (all, allSettled) or the errors array (any). All settled values are held until the combinator itself settles.
Common mistakes to call out:
- Passing
[]toPromise.anyin a code path where the mirror list could be empty — it rejects immediately, which surprises people. - Non-promise values in the iterable work fine; they're treated as already-fulfilled.
fetchresolves even on 4xx/5xx. Always checkr.okand throw, otherwise an HTTP error counts as a "success" foranyandall.- Adding per-request timeouts (
AbortSignal.timeout) alongside a combinator timeout preventsallSettledfrom hanging on a never-responding service.