Sub topic 7
Reading Settled Results and Reporting Partial Failure
Promise.allSettled never rejects. That is why it is useful, and it also creates a risk. Every failure ends up inside the result array, and if you never look there, you never learn about it. This chapter covers how to read the settled result objects correctly, connect each result to the input that produced it, split successes from failures, and decide what "partly worked" means for your program.
This chapter assumes you know async functions, await, try/catch, and array methods such as map, filter, and forEach, and that you have read the previous chapter's introduction to Promise.allSettled. The examples use top-level await, so run them as ES modules: save them as .mjs files in Node.js 14.8 or later, or paste them into a browser console.
The Shape of a Settled Result
Each element of the array that Promise.allSettled returns is a plain object in one of two shapes:
| `status` | Other property | Meaning |
|---|---|---|
| `'fulfilled'` | `value` | The input fulfilled with this value |
| `'rejected'` | `reason` | The input rejected with this reason |
A fulfilled object never has a reason property, and a rejected object never has a value property. The status string is the only field that is present in both shapes and always tells you which one you have.
Real values are often awkward. Here are a few:
const outcomes = await Promise.allSettled([
Promise.resolve(0),
Promise.resolve(undefined),
Promise.reject('plain string'),
Promise.reject(undefined)
]);
console.log(outcomes);
// [
// { status: 'fulfilled', value: 0 },
// { status: 'fulfilled', value: undefined },
// { status: 'rejected', reason: 'plain string' },
// { status: 'rejected', reason: undefined }
// ]Every one of these is legal JavaScript. A fulfilled value can be 0, '', false, null, or undefined. A rejection reason can be any value at all, not just an Error.
Always Branch on `status`
The most common bug is to check the payload instead of the status:
const outcomes = await Promise.allSettled([
Promise.resolve(0),
Promise.reject(undefined)
]);
// Wrong: treats a fulfilled 0 as a failure
const wrongValues = outcomes.filter((o) => o.value).map((o) => o.value);
console.log(wrongValues); // []
// Wrong: misses a rejection whose reason is undefined
const wrongFailures = outcomes.filter((o) => o.reason);
console.log(wrongFailures.length); // 0
// Right
const values = outcomes.filter((o) => o.status === 'fulfilled').map((o) => o.value);
const failures = outcomes.filter((o) => o.status === 'rejected');
console.log(values); // [0]
console.log(failures.length); // 1In TypeScript, the built-in PromiseSettledResult<T> type is a discriminated union, so checking status narrows the type. A type guard lets filter keep that narrowing:
function fulfilledValues<T>(outcomes: PromiseSettledResult<T>[]): T[] {
return outcomes
.filter((o): o is PromiseFulfilledResult<T> => o.status === 'fulfilled')
.map((o) => o.value);
}
function rejectedReasons<T>(outcomes: PromiseSettledResult<T>[]): unknown[] {
return outcomes
.filter((o): o is PromiseRejectedResult => o.status === 'rejected')
.map((o) => o.reason);
}Note that PromiseRejectedResult['reason'] is typed any. Treat it as unknown and inspect it before using it.
Connecting Results to Their Inputs
A result object does not say which input it came from. Only its position tells you that: outcomes[i] belongs to input i, whatever order the inputs finished in. To report useful failures, keep the input list and look results up by index.
function fakeRequest(name, ms, ok) {
return new Promise((resolve, reject) =>
setTimeout(
() => (ok ? resolve({ name, rows: ms }) : reject(new Error(`${name} unavailable`))),
ms
)
);
}
const sources = [
{ name: 'users', load: () => fakeRequest('users', 80, true) },
{ name: 'orders', load: () => fakeRequest('orders', 30, false) },
{ name: 'inventory', load: () => fakeRequest('inventory', 50, true) }
];
const outcomes = await Promise.allSettled(sources.map((s) => s.load()));
const succeeded = [];
const failed = [];
outcomes.forEach((outcome, i) => {
const { name } = sources[i];
if (outcome.status === 'fulfilled') {
succeeded.push({ name, value: outcome.value });
} else {
failed.push({ name, reason: outcome.reason });
}
});
console.log(succeeded.map((s) => s.name)); // ['users', 'inventory']
console.log(failed.map((f) => f.name)); // ['orders']orders finished first, but it still sits at index 1, so the lookup is correct.
Turning Reasons into Readable Messages
Reasons come from code you may not control. A library might reject with an Error, a string, a response object, or nothing. A small helper keeps your reporting safe:
function describeReason(reason) {
if (reason instanceof Error) return reason.message;
if (typeof reason === 'string') return reason;
if (reason === undefined) return '(no reason given)';
try {
return JSON.stringify(reason);
} catch {
return String(reason);
}
}
console.log(describeReason(new Error('timeout'))); // timeout
console.log(describeReason('bad input')); // bad input
console.log(describeReason(undefined)); // (no reason given)
console.log(describeReason({ code: 503 })); // {"code":503}For logs that people will read, a message is enough. For error tracking, keep the original Error object as well so the stack trace survives.
Deciding What Partial Failure Means
allSettled gives you every outcome. It does not decide whether the overall operation succeeded. You have to set that policy yourself, and you should write it down in code rather than leave it implied.
Here is that policy as a reusable function:
async function settleWithPolicy(tasks, { maxFailures = Infinity } = {}) {
const outcomes = await Promise.allSettled(tasks.map((t) => t.run()));
const succeeded = [];
const failed = [];
outcomes.forEach((outcome, i) => {
const name = tasks[i].name;
if (outcome.status === 'fulfilled') {
succeeded.push({ name, value: outcome.value });
} else {
failed.push({ name, reason: outcome.reason });
}
});
if (failed.length > 0) {
const summary = failed
.map((f) => `${f.name}: ${f.reason instanceof Error ? f.reason.message : String(f.reason)}`)
.join('; ');
if (succeeded.length === 0 || failed.length > maxFailures) {
throw new AggregateError(
failed.map((f) => f.reason),
`${failed.length} of ${tasks.length} tasks failed: ${summary}`
);
}
console.warn(`Partial failure (${failed.length}/${tasks.length}): ${summary}`);
}
return { succeeded, failed };
}
const tasks = [
{ name: 'a', run: () => Promise.resolve(1) },
{ name: 'b', run: () => Promise.reject(new Error('disk full')) },
{ name: 'c', run: () => Promise.resolve(3) }
];
const { succeeded } = await settleWithPolicy(tasks, { maxFailures: 1 });
// Partial failure (1/3): b: disk full
console.log(succeeded.map((s) => s.value)); // [1, 3]
try {
await settleWithPolicy(tasks, { maxFailures: 0 });
} catch (err) {
console.log(err.message); // 1 of 3 tasks failed: b: disk full
}Returning failed alongside succeeded lets the caller retry just the failed tasks or show them in a user interface. Throwing an AggregateError (covered in depth in a later chapter) keeps every original reason in err.errors.
Common Mistakes
- Wrapping
allSettledintry/catchand assuming failures will land incatch. They never do, because the returned promise always fulfills. Task failures appear only in the result array. - Using truthiness to detect success. As shown above,
0,'', andundefinedare valid values and reasons. - Assuming
reasonis anError. Readingreason.messageon a string givesundefined, and on anundefinedreason it throws aTypeErrorinside your error handler. - Losing the index. Results filtered before you attach names cannot be traced back to their inputs.
- Silently dropping failures. If you discard rejected entries without logging or returning them,
allSettledis hiding errors thatPromise.allwould have shown you.
Exercise
A teammate writes const ok = outcomes.filter((o) => o.value !== undefined) to keep successful results. Give one input that this gets wrong, and write the correct filter.
Show answer
Promise.resolve(undefined) fulfills, but its value is undefined, so the filter drops a success. (Rejected objects have no value, so they are excluded correctly, but only by accident.) The correct filter is outcomes.filter((o) => o.status === 'fulfilled').
Exercise
Given const urls = ['a', 'b', 'c'] and const outcomes = await Promise.allSettled(urls.map(load)), write code that builds an array of only the URLs whose load failed, so they can be retried.
Show answer
const toRetry = urls.filter((_, i) => outcomes[i].status === 'rejected'); This works because outcomes[i] always matches urls[i], whatever order the loads finished in.
Exercise
What does this print, and why? try { const r = await Promise.allSettled([Promise.reject(new Error('x'))]); console.log('done', r[0].status); } catch { console.log('caught'); }
Show answer
It prints done rejected. Promise.allSettled fulfills even when every input rejects, so the catch block never runs. The failure appears only as { status: 'rejected', reason: Error('x') } in the result array.