Sub topic 7
Reading Settled Results and Reporting Partial Failure
This chapter assumes you know how Promise.allSettled waits for every input. It also assumes you are comfortable with array methods such as map and filter, with destructuring, and with async/await. The focus here is what to do with the array that allSettled gives back.
The Shape of a Settled Result
Each element of the result array is a plain object that describes one input. The element sits at the same index as its input. There are only 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 has no reason property, and a rejected object has no value property. Always branch on status. Testing whether value is truthy gives wrong answers when a promise legitimately fulfills with undefined, 0, or ''.
Splitting Successes from Failures
The usual first step is to partition the outcomes. Keep the input index, or better an identifying key, so a failure can be traced back to the task that caused it. On its own, the outcome object doesn't say which input it came from. Only its position in the array tells you that.
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function loadUser(id) {
await delay(20);
if (id === 2) throw new Error(`User ${id} not found`);
if (id === 4) throw 'timeout'; // a non-Error rejection reason
return { id, name: `user${id}` };
}
async function main() {
const ids = [1, 2, 3, 4];
const outcomes = await Promise.allSettled(ids.map(loadUser));
const successes = [];
const failures = [];
outcomes.forEach((outcome, i) => {
if (outcome.status === 'fulfilled') {
successes.push(outcome.value);
} else {
const reason = outcome.reason;
const message = reason instanceof Error ? reason.message : String(reason);
failures.push({ id: ids[i], message });
}
});
console.log(`Loaded ${successes.length} of ${ids.length} users`);
for (const f of failures) {
console.log(` id ${f.id} failed: ${f.message}`);
}
}
main();
// Loaded 2 of 4 users
// id 2 failed: User 2 not found
// id 4 failed: timeoutDeciding What Partial Failure Means
allSettled never rejects, so your code has to decide which outcomes count as a failure. Common policies:
- Best effort: use whatever succeeded and log the failures. This suits dashboards and prefetching.
- Threshold: carry on only if enough tasks succeeded, and throw otherwise.
- All failed: throw only when nothing succeeded, so the caller still sees an error.
If you throw, put the individual reasons on the error you raise. An AggregateError fits this case well:
function requireSome(outcomes) {
const values = outcomes.filter((o) => o.status === 'fulfilled').map((o) => o.value);
if (values.length === 0) {
const reasons = outcomes.map((o) => o.reason);
throw new AggregateError(reasons, 'Every task failed');
}
return values;
}Common Errors
- Reading
outcome.valuewithout checkingstatus, which silently yieldsundefinedfor rejected entries. - Filtering out the failures first and then using
ifrom the filtered array to look up inputs. Those indexes no longer match the original input order. - Using
allSettledand then never looking at the rejected entries, which hides errors as thoroughly as an emptycatchdoes.
Exercise
A task list is ['a', 'b', 'c'], and Promise.allSettled returns [{status:'fulfilled', value:undefined}, {status:'rejected', reason:null}, {status:'fulfilled', value:0}]. A colleague counts successes with outcomes.filter(o => o.value).length and builds messages with o.reason.message. What goes wrong, and what should they write instead?
Show answer
The filter counts 0 successes because undefined and 0 are falsy, when there are really 2. Reading null.message throws a TypeError. They should count with outcomes.filter(o => o.status === 'fulfilled').length and build messages with o.reason instanceof Error ? o.reason.message : String(o.reason), which gives 'null' for task 'b'.