Promise.allSettled(): handle partial failures (ES2020)
What you’ll learn
Section titled “What you’ll learn”- What
Promise.allSettled()returns and how its{ status, value | reason }result objects are shaped. - How to load independent resources in parallel and report partial failure instead of losing every result.
- How to narrow settled results safely in TypeScript.
- How to combine it with fail-fast required data, cancellation and a concurrency limit.
- When it is the wrong tool, and how it compares with
Promise.all(),Promise.any()andPromise.race().
Summary
Section titled “Summary”TL;DR: Promise.allSettled(iterable) returns a promise that fulfills once every input has settled (fulfilled or rejected). It fulfills with an array, in input order, of objects that are either { status: "fulfilled", value } or { status: "rejected", reason }. One failure never discards the other results.
It was added in ECMAScript 2020 and is supported by every current browser and server runtime (details in Compatibility).
The problem it solves
Section titled “The problem it solves”Promise.all() is fail-fast: it rejects as soon as any input rejects. That is right when the results depend on each other, and wrong when the tasks are independent. If CustomerDashboard loads a profile, recent orders and alerts, one broken service should not blank the whole page.
Running the samples: the JavaScript samples on this page are ES modules that use top-level await. Save one as a .mjs file and run it with Node.js 22 (except where noted) (node sample.mjs), or paste it into a browser console. All outputs shown were produced with Node.js 22.23.
const wait = (ms, value, fail = false) => new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms));
// Before: Promise.all rejects as soon as one input rejects.try { const [profile, orders, alerts] = await Promise.all([ wait(30, 'profile'), wait(10, 'orders service unavailable', true), wait(20, 'alerts'), ]); console.log(profile, orders, alerts);} catch (error) { console.log('Promise.all rejected:', error.message); // The profile and alerts results are lost, even though they arrive.}
// After: Promise.allSettled waits for every input and reports each outcome.const results = await Promise.allSettled([ wait(30, 'profile'), wait(10, 'orders service unavailable', true), wait(20, 'alerts'),]);console.log(results);Output (stack trace shortened):
Promise.all rejected: orders service unavailable[ { status: 'fulfilled', value: 'profile' }, { status: 'rejected', reason: Error: orders service unavailable ... }, { status: 'fulfilled', value: 'alerts' }]How it works
Section titled “How it works”// Fragment: signature and result shapeconst results = await Promise.allSettled(iterable);// results: Array<// | { status: 'fulfilled', value: any }// | { status: 'rejected', reason: any }// >- Input is any iterable: an array, a
Set, a generator. Each element goes throughPromise.resolve(), so plain values and thenables both work. - Output is a promise for an array with one entry per input, in input order, not completion order.
- A fulfilled entry has
statusandvalue; a rejected entry hasstatusandreason. The other property is absent, so checkstatus, notvalue.
| Input | Result |
|---|---|
[] |
fulfills with [] |
[42, 'text', null] |
three fulfilled entries holding the plain values |
| promises that settle out of order | entries in input order |
| a generator that yields a rejected promise | a rejected entry for it; the others still fulfill |
a non-iterable such as 123 |
the returned promise rejects with a TypeError |
an iterator whose next() throws |
the returned promise rejects with that error |
console.log(await Promise.allSettled([])); // []
console.log(await Promise.allSettled([42, 'text', null]));// [ { status: 'fulfilled', value: 42 }, { status: 'fulfilled', value: 'text' },// { status: 'fulfilled', value: null } ]
const slow = new Promise((r) => setTimeout(() => r('slow'), 20));const fast = new Promise((r) => setTimeout(() => r('fast'), 5));console.log((await Promise.allSettled([slow, fast])).map((r) => r.value)); // [ 'slow', 'fast' ]
function* jobs() { yield 1; yield Promise.reject(new Error('job 2 failed')); }console.log(await Promise.allSettled(jobs()));// [ { status: 'fulfilled', value: 1 },// { status: 'rejected', reason: Error: job 2 failed ... } ]
try { await Promise.allSettled(123);} catch (error) { console.log(error.constructor.name, '-', error.message); // TypeError - number 123 is not iterable (cannot read property Symbol(Symbol.iterator))}
function* broken() { yield 1; throw new Error('iterator blew up'); }try { await Promise.allSettled(broken());} catch (error) { console.log('rejected:', error.message); // rejected: iterator blew up}The TypeError message is V8’s wording and differs between engines.
When the returned promise rejects
Section titled “When the returned promise rejects”The popular claim that “allSettled never rejects” is true only for its inputs. In practice the returned promise rejects when the argument is not iterable or when the iterator throws. The specification also rejects it when the constructor’s resolve is not callable or throws, or when calling .then on an element throws; those cases need a custom Promise subclass or a hostile thenable. Calling it with a this that is not a constructor, as in Promise.allSettled.call(undefined, []), throws a TypeError synchronously.
Spec details you can observe
Section titled “Spec details you can observe”The algorithm is Promise.allSettled plus PerformPromiseAllSettled in the ECMAScript specification:
- Each callback writes a fresh
{ status, value }or{ status, reason }object into the slot at its input’s index, which is why order is preserved. - The fulfilled and rejected callbacks for one element share one “already called” flag, so a thenable that calls both, or calls one twice, records a single result.
- If
next()itself throws, the iterator is treated as done and itsreturn()method is not called. If a later step fails (the constructor’sresolvethrows, or calling.thenthrows), the iterator is closed withreturn()before the promise rejects.
TypeScript
Section titled “TypeScript”TypeScript models each entry as PromiseSettledResult<T>, a discriminated union of PromiseFulfilledResult<T> and PromiseRejectedResult. Checking status narrows the union. This version of CustomerDashboard’s order list uses named type guards, which make filter narrow in every TypeScript version:
interface Order { id: string; total: number }interface Invoice { orderId: string; pdfUrl: string }
function isFulfilled<T>(r: PromiseSettledResult<T>): r is PromiseFulfilledResult<T> { return r.status === 'fulfilled';}
function isRejected<T>(r: PromiseSettledResult<T>): r is PromiseRejectedResult { return r.status === 'rejected';}
async function fetchOrder(id: string): Promise<Order> { if (id === 'o-2') throw new Error(`order ${id} not found`); return { id, total: id.length * 10 };}
async function fetchInvoice(orderId: string): Promise<Invoice> { return { orderId, pdfUrl: `https://files.example.test/${orderId}.pdf` };}
async function main(): Promise<void> { // Array input: every element has the same type -> PromiseSettledResult<Order>[] const results = await Promise.allSettled(['o-1', 'o-2', 'o-3'].map(fetchOrder));
const orders: Order[] = results.filter(isFulfilled).map((r) => r.value); const errors: unknown[] = results.filter(isRejected).map((r) => r.reason); console.log(orders.length, 'orders loaded;', errors.length, 'failed');
// Array literal: TypeScript infers a tuple, so each position keeps its own type. const [orderResult, invoiceResult] = await Promise.allSettled([ fetchOrder('o-1'), fetchInvoice('o-1'), ]);
if (orderResult.status === 'fulfilled') { console.log(orderResult.value.total); // Order } if (invoiceResult.status === 'fulfilled') { console.log(invoiceResult.value.pdfUrl); // Invoice } else { // reason is typed as `any`; treat it as unknown and check before use. const reason: unknown = invoiceResult.reason; console.log(reason instanceof Error ? reason.message : String(reason)); }}
main();Output: 2 orders loaded; 1 failed, then 30, then https://files.example.test/o-1.pdf. This sample type-checks with tsc --noEmit --strict --target es2022 --lib es2022,dom on TypeScript 6.0.3 and 7.0.2.
Two typing details matter. First, PromiseRejectedResult.reason is any, because JavaScript can reject with any value; assign it to unknown and check it. Second, since TypeScript 5.5 an inline callback such as r => r.status === 'fulfilled' is inferred as a type predicate, so filter narrows without a named guard. On TypeScript 5.4 and earlier the same code fails with Property 'value' does not exist on type 'PromiseSettledResult<number>'.
Realistic example
Section titled “Realistic example”CustomerDashboard loads four independent widgets from an invented API at api.example.test. The profile is required; the other widgets are optional. Each request gets a timeout through AbortSignal.timeout(), combined with an optional caller signal through AbortSignal.any(), and HTTP errors become rejections because fetch rejects only on network failures.
// dashboard.mjs - load independent CustomerDashboard widgets in parallel.export const API = 'https://api.example.test';
const widgets = [ { id: 'profile', url: `${API}/me`, required: true }, { id: 'orders', url: `${API}/orders?limit=5` }, { id: 'recommendations', url: `${API}/recommendations` }, { id: 'notifications', url: `${API}/notifications` },];
export async function getJson(url, { timeoutMs = 3000, signal } = {}) { const timeout = AbortSignal.timeout(timeoutMs); const response = await fetch(url, { signal: signal ? AbortSignal.any([signal, timeout]) : timeout }); if (!response.ok) { // fetch only rejects on network errors; turn HTTP errors into rejections. throw new Error(`GET ${url} failed with HTTP ${response.status}`); } return response.json();}
export function describeFailure(reason) { if (reason instanceof DOMException && reason.name === 'TimeoutError') return 'timed out'; return reason instanceof Error ? reason.message : String(reason);}
export async function loadDashboard() { const results = await Promise.allSettled(widgets.map((w) => getJson(w.url)));
const data = {}; const failures = []; results.forEach((result, i) => { const widget = widgets[i]; // results are in input order if (result.status === 'fulfilled') { data[widget.id] = result.value; } else { failures.push({ id: widget.id, required: Boolean(widget.required), error: describeFailure(result.reason) }); } });
const fatal = failures.find((f) => f.required); if (fatal) { // Partial success is fine for optional widgets, not for the page's core data. throw new Error(`Cannot render dashboard: ${fatal.id} ${fatal.error}`); } return { data, failures };}With a mocked fetch where orders returns HTTP 503 and recommendations never answers, loadDashboard() resolves after about three seconds (the timeout) with:
data: { profile: { name: 'Ada' }, notifications: [ { id: 1 } ] }failures: [ { id: 'orders', required: false, error: 'GET https://api.example.test/orders?limit=5 failed with HTTP 503' }, { id: 'recommendations', required: false, error: 'timed out' } ]If the profile request fails instead, it throws Cannot render dashboard: profile GET https://api.example.test/me failed with HTTP 500. Map results back by index, decide what is fatal after settling (or fail fast on required data, see Production patterns), and always bound the wait.
Production patterns
Section titled “Production patterns”Fail fast on required data, settle the optional data
Section titled “Fail fast on required data, settle the optional data”loadDashboard() waits up to three seconds before it can report that the profile failed. Nesting allSettled inside Promise.all fails as soon as the required request fails, while the optional widgets still report partial failure. Because the other inputs keep running after Promise.all rejects (see When to use it and when not to), one shared AbortController stops them:
import { API, getJson } from './dashboard.mjs';
// Required data fails fast; optional widgets settle; one controller cancels stragglers.export async function loadDashboardFast() { const controller = new AbortController(); const { signal } = controller; const optionalUrls = [`${API}/orders?limit=5`, `${API}/recommendations`, `${API}/notifications`]; try { const [profile, optional] = await Promise.all([ getJson(`${API}/me`, { signal }), Promise.allSettled(optionalUrls.map((url) => getJson(url, { signal }))), ]); return { profile, optional }; } catch (error) { controller.abort(); // without this, the optional requests keep running throw error; }}With the profile failing after 20 ms and recommendations taking 200 ms, the call rejects with GET https://api.example.test/me failed with HTTP 500, and the mock’s request log ends with aborted https://api.example.test/recommendations. Without controller.abort() it ends with done https://api.example.test/recommendations: wasted work.
Aggregate failures into one error
Section titled “Aggregate failures into one error”When a caller needs a single thrown error, or your logger expects one, wrap the rejection reasons in an AggregateError (ES2021). It keeps every original error in its errors array. For a single wrapped error, use Error Cause instead.
const results = await Promise.allSettled([ Promise.resolve({ id: 'profile' }), Promise.reject(new Error('orders: HTTP 503')), Promise.reject(new Error('recommendations: timed out')),]);
const reasons = results.filter((r) => r.status === 'rejected').map((r) => r.reason);if (reasons.length > 0) { const error = new AggregateError(reasons, `${reasons.length} of ${results.length} dashboard widgets failed`); console.log(error.message); // 2 of 3 dashboard widgets failed console.log(error.errors.map((e) => e.message)); // [ 'orders: HTTP 503', 'recommendations: timed out' ]}Limit concurrency
Section titled “Limit concurrency”allSettled does not schedule anything; the work starts when the promises are created. To load many items without flooding the API, pass functions to a small worker pool and collect results in the same shape:
// allSettled semantics with at most `limit` tasks in flight at once.// `tasks` are functions that start the work, so nothing runs before we call them.export async function allSettledLimit(tasks, limit = 4) { const results = new Array(tasks.length); let next = 0;
async function worker() { while (next < tasks.length) { const i = next++; // safe: JavaScript runs this synchronously on one thread try { results[i] = { status: 'fulfilled', value: await tasks[i]() }; } catch (reason) { results[i] = { status: 'rejected', reason }; } } }
await Promise.all(Array.from({ length: Math.min(limit, tasks.length) }, worker)); return results;}
// Demo: load 10 order details for the dashboard, at most 3 requests in flight, every 4th one fails.let inFlight = 0;let peak = 0;const tasks = Array.from({ length: 10 }, (_, n) => async () => { inFlight++; peak = Math.max(peak, inFlight); await new Promise((r) => setTimeout(r, 10)); inFlight--; if (n % 4 === 3) throw new Error(`order o-${n}: HTTP 503`); return `o-${n}`;});
const results = await allSettledLimit(tasks, 3);console.log('peak concurrency:', peak); // peak concurrency: 3console.log(results.map((r) => (r.status === 'fulfilled' ? r.value : `ERR ${r.reason.message}`)));// [ 'o-0', 'o-1', 'o-2', 'ERR order o-3: HTTP 503', 'o-4', 'o-5', 'o-6', 'ERR order o-7: HTTP 503', 'o-8', 'o-9' ]Promise.all is safe for the workers because each worker catches its own errors.
Common mistakes
Section titled “Common mistakes”-
Ignoring
status.results.map(r => r.value)silently turns every failure intoundefined. Filter onstatusand log the reasons. -
Assuming it can never reject. A bad iterable or a throwing iterator rejects the returned promise (see When the returned promise rejects).
-
Unbounded concurrency.
Promise.allSettled(tenThousandIds.map(fetchItem))starts ten thousand requests at once and can exhaust sockets or hit rate limits. Use a concurrency limit. -
Memory with huge inputs. Every value or reason is held until the last input settles. Process large inputs in batches.
-
No timeout. The result waits for the slowest input; one hung request hangs the caller. Give each task a timeout.
-
No cancellation.
allSettlednever cancels the remaining work. Pass anAbortSignalto the tasks. -
Synchronous throws escape it. If a function throws while you build the input array, the exception is thrown before
allSettledis called. Make the functionasync, or wrap each call withPromise.try()(ES2025), which turns a synchronous throw into a rejection:function loadReport(id) {if (!id) throw new TypeError('id is required');return Promise.resolve({ id });}// ['r1', '', 'r3'].map(loadReport) would throw before allSettled runs.const results = await Promise.allSettled(['r1', '', 'r3'].map((id) => Promise.try(loadReport, id)));console.log(results.map((r) => r.status)); // [ 'fulfilled', 'rejected', 'fulfilled' ]Promise.tryneeds Node.js 23 or later (this sample was run on Node.js 24.22); on Node.js 22 it fails withTypeError: Promise.try is not a function. -
Rejections before
allSettledsees them. Handlers are attached only whenallSettledis called. A promise that rejects while youawaitsomething else first is reported as unhandled. Since Node.js 15 the default (--unhandled-rejections=throw) crashes the process; browsers fire anunhandledrejectionevent and log a console error, then arejectionhandledevent when the handler is attached later. Create promises immediately before passing them in.// Fragment: crashes Node.js before allSettled runsconst audit = Promise.reject(new Error('audit service down'));await new Promise((r) => setTimeout(r, 10)); // other async work firstconst results = await Promise.allSettled([audit]); // too late
When to use it and when not to
Section titled “When to use it and when not to”| Combinator | Settles when | Fulfills with | Rejects when | Typical use |
|---|---|---|---|---|
Promise.all (ES2015) |
all fulfill, or the first rejects | array of values | the first input rejects | dependent results; all-or-nothing |
Promise.allSettled (ES2020) |
every input has settled | array of { status, value | reason } |
in practice, only for a bad iterable or throwing iterator | independent tasks; partial success |
Promise.any (ES2021) |
the first fulfills, or all reject | the first fulfilled value | all inputs reject (AggregateError) |
redundant sources, fastest mirror |
Promise.race (ES2015) |
the first input settles | that value | the first input to settle rejects | timeouts, first response wins |
When Promise.all rejects, the other inputs keep running; it simply stops waiting for them. Their later rejections are not reported as unhandled, because Promise.all has already attached handlers to every input.
Use allSettled for independent tasks where partial results are useful. Choose something else when:
- The results depend on each other, such as a checkout that needs both price and stock. Use
Promise.alland fail fast. - One successful answer is enough. Use
Promise.any. - The whole group needs a deadline.
allSettledhas no timeout; put one on each task or race the group against a timer. - The work is sequential, each step using the previous result. Use
awaitin a loop. - You want to react as each result arrives, for example to render widgets progressively. Handle each promise with its own
.then.
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, Promise.allSettled is supported in Chrome 76, Edge 79, Firefox 71, Safari 13 (including iOS), Node.js 12.9.0, Deno 1.0 and Bun 1.0. Internet Explorer never supported it. The examples also use AbortSignal.any(), which needs Node.js 20.3+ or a current browser.
TypeScript: the types live in lib.es2020.promise.d.ts; TypeScript 7.0 ships the identical file. The default target in TypeScript 6.0 and 7.0 already includes ES2020, so you only need to act if a project pins an older target or lib: add es2020 or later to lib. TypeScript never polyfills runtime methods.
Polyfill: for older runtimes, use a maintained polyfill such as core-js. The shim below is what developers wrote by hand before ES2020; it shows the semantics but is not spec-complete (it ignores subclassing and iterator closing):
// Minimal illustration of the semantics, NOT a spec-complete polyfill.function allSettledShim(iterable) { return Promise.all( Array.from(iterable, (item) => Promise.resolve(item).then( (value) => ({ status: 'fulfilled', value }), (reason) => ({ status: 'rejected', reason }), ), ), );}
console.log(await allSettledShim([1, Promise.reject(new Error('x')), Promise.resolve(3)]));// [ { status: 'fulfilled', value: 1 }, { status: 'rejected', reason: Error: x ... },// { status: 'fulfilled', value: 3 } ]Interview questions
Section titled “Interview questions”1. What is the difference between Promise.all and Promise.allSettled?
Promise.all fulfills with an array of values only if every input fulfills, and rejects with the first rejection reason. Promise.allSettled waits for every input and fulfills with one { status, value } or { status, reason } object per input, in input order. Use all for all-or-nothing work and allSettled for independent tasks.
2. Can Promise.allSettled ever reject?
Yes. Rejected inputs never reject it, but in practice it rejects when the argument is not iterable or the iterator throws. The spec also rejects when the constructor’s resolve or an element’s then throws, and a non-constructor this throws synchronously.
3. Does allSettled run the promises in parallel?
It does not run anything; it observes promises that are already running. Work starts when the promises are created, usually all at once in a .map. To limit concurrency, give a worker pool functions instead of promises.
4. How do you get only the successful values in TypeScript with correct types?
Filter on status and map to r.value. TypeScript 5.5 and later infer the predicate from r => r.status === 'fulfilled'; on older versions you need an explicit guard such as (r): r is PromiseFulfilledResult<T> => r.status === 'fulfilled'.
5. Why can a rejection be reported as unhandled even though you pass it to allSettled?
Handlers are attached only when allSettled is called. A promise that rejected earlier, while you awaited something else, already had no handler: Node.js crashes by default and browsers fire unhandledrejection.
6. Senior scenario: a page needs one required data source and five optional ones, must render within two seconds, and must not waste backend capacity. How do you design the loading?
Start all requests at once with a shared AbortController. Wrap the optional requests in Promise.allSettled and combine that with the required request in Promise.all, so a required failure fails fast. Give every request a timeout (AbortSignal.timeout, combined with the shared signal through AbortSignal.any) to bound latency. On a required failure, call abort() so stragglers stop; on success, render the optional widgets that fulfilled and show a fallback plus a logged error for each rejected one. If the optional set can grow large, add a concurrency limit.
Key takeaways
Section titled “Key takeaways”Promise.allSettled(ES2020) waits for every input and fulfills with one{ status, value | reason }object per input, in input order.- Use it for independent tasks where partial success is useful; use
Promise.allwhen one failure makes the rest worthless, or nest the two. - Rejected inputs never reject it, but a bad iterable or throwing iterator does. You still have to inspect every result.
- It does not limit concurrency, add timeouts or cancel work. Add those with a worker pool,
AbortSignal.timeout()and anAbortController. - In TypeScript, narrow on
statusand treatreasonasunknown.
Related pages
Section titled “Related pages”- Promises: the promise model that all combinators build on.
- Promise.any: the “first success wins” combinator from ES2021.
- Promise.finally: clean-up that runs regardless of outcome.
- Async/Await: the syntax used in every example on this page.
- Error Cause: attach the original error when you wrap a failure.
- Async Iteration: processing results as a stream instead of all at once.
- TypeScript Async/Await: typing asynchronous code in TypeScript.
- JavaScript interview questions
Official references
Section titled “Official references”- ECMAScript Language Specification,
Promise.allSettled ( iterable )(current draft; first published in ECMAScript 2020, 11th edition) - ECMAScript 2020 Language Specification (ECMA-262, 11th edition)
- TC39 proposal: Promise.allSettled
- MDN: Promise.allSettled()
- MDN: Promise.try()
- MDN: AggregateError
- MDN: AbortSignal.timeout() and AbortSignal.any()
- MDN: Window
unhandledrejectionevent - Node.js 22 CLI:
--unhandled-rejections - TypeScript 6.0.3:
lib.es2020.promise.d.ts