Sub topic 6
Promise.allSettled: Collect Every Outcome
This chapter assumes you know how Promise.all works and how it rejects on the first failure, both covered in the previous two chapters. It also assumes you are comfortable with async/await and try/catch. The examples use top-level await, so run them as ES modules (save the file with an .mjs extension in Node.js) or paste them into a browser console.
Why another "wait for all" combinator?
Promise.all answers one question: "Did everything succeed?" If one input rejects, you get that one reason and lose every other result. That is the right behavior when the results only make sense together. Charging a card and reserving stock for the same order is an example.
Many batches don't work that way. A dashboard might load six widgets from six services. If the weather service is down, you still want to show the other five and mark one as unavailable. A script that sends 200 notification emails needs to know which 7 failed. Stopping at the first failure doesn't help it. For these cases you need every outcome, successes and failures alike. Promise.allSettled provides that.
How allSettled decides when to settle
Promise.allSettled(iterable) returns one promise. It follows these rules:
- It waits until every input has settled, whether fulfilled or rejected.
- It then fulfills with an array that holds one result object per input, in input order.
- It never rejects because an input rejected. A rejection is recorded in the array like any other result.
Each result object has one of two shapes:
| Input outcome | Result object |
|---|---|
| Fulfilled with `v` | `{ status: 'fulfilled', value: v }` |
| Rejected with `r` | `{ status: 'rejected', reason: r }` |
The next chapter shows how to read these objects and build failure reports. This chapter covers the settling behavior.
A worked example
The helper below resolves or rejects after a delay, so you can see the timing.
const delay = (ms, value, fail = false) =>
new Promise((resolve, reject) =>
setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms)
);
const started = Date.now();
const outcomes = await Promise.allSettled([
delay(300, 'profile'),
delay(50, 'avatar service down', true),
delay(150, 'settings'),
42
]);
console.log(`took about ${Date.now() - started} ms`); // took about 300 ms
console.log(outcomes.map((o) => o.status));
// [ 'fulfilled', 'rejected', 'fulfilled', 'fulfilled' ]
console.log(outcomes[1].reason.message); // avatar service down
console.log(outcomes[3]); // { status: 'fulfilled', value: 42 }This example shows four behaviors:
- The rejection at 50 ms doesn't end the wait. The returned promise settles at about 300 ms, when the slowest input finishes.
- The order of the results matches the order of the inputs. Finishing order doesn't affect it.
- The plain value
42is treated as an already-fulfilled promise, just asPromise.alltreats it. - The rejection reason is the original
Errorobject, so you keep its message and stack trace.
Side by side with Promise.all
Here are the same inputs passed to both combinators:
const makeInputs = () => [
Promise.resolve('a'),
Promise.reject(new Error('b failed')),
Promise.resolve('c')
];
try {
await Promise.all(makeInputs());
} catch (err) {
console.log('all rejected:', err.message); // all rejected: b failed
}
const settled = await Promise.allSettled(makeInputs());
console.log(settled.filter((o) => o.status === 'fulfilled').map((o) => o.value));
// [ 'a', 'c' ]| Question | `Promise.all` | `Promise.allSettled` |
|---|---|---|
| When does it settle? | When all inputs fulfill, or at the first rejection | When every input has settled |
| Can an input make it reject? | Yes, the first rejection does | No |
| Fulfillment value | Array of plain values | Array of `{ status, value }` or `{ status, reason }` objects |
| Results you get if one input fails | One reason | Every value and every reason |
| How long it waits | Up to the slowest input, or less if an input rejects | Always as long as the slowest input |
How it works inside
You can build allSettled from Promise.all. Turn each input into a promise that always fulfills with a result object, then wait for all of them:
function allSettled(iterable) {
return Promise.all(
[...iterable].map((item) =>
Promise.resolve(item).then(
(value) => ({ status: 'fulfilled', value }),
(reason) => ({ status: 'rejected', reason })
)
)
);
}
const results = await allSettled([Promise.reject(new Error('x')), 1]);
console.log(results[0].status, results[1].value); // rejected 1The rejection handler turns every rejection into a fulfillment, so the wrapped Promise.all can never fail fast. This is how polyfills implemented allSettled before it became part of ES2020. One difference: this sketch throws synchronously when you pass something that isn't iterable. The built-in version returns a rejected promise in that case.
Common errors
Wrapping it in try/catch and expecting failures to land there
try {
const results = await Promise.allSettled([Promise.reject(new Error('lost'))]);
console.log('no error thrown; results[0].status is', results[0].status);
} catch (err) {
console.log('this never runs for input rejections');
}The catch block only runs if allSettled itself fails. That happens when the argument isn't iterable, for example Promise.allSettled(123) rejects with a TypeError. To find failed inputs, check the status of each result.
Reading `.value` without checking `status`
A rejected result has no value property, so outcome.value is undefined. Code that does results.map((o) => o.value) quietly turns every failure into undefined. That is worse than a crash, because nothing tells you a failure happened. Always branch on status first.
Ignoring the failures entirely
allSettled makes it easy to drop errors without noticing. If you only filter for fulfilled results, at least log or count the rejected ones. Otherwise a service can fail for weeks before anyone finds out.
Expecting it to finish early
allSettled waits for every input, including one that never settles. A single request that hangs keeps the whole batch pending forever. If an input can hang, give it a timeout first. The timeout pattern with Promise.race comes later in this tutorial.
This is the risky ordering:
const fails = () => Promise.reject(new Error('early'));
const slow = () => new Promise((resolve) => setTimeout(resolve, 100));
const risky = fails(); // rejects now, with no handler attached yet
await slow(); // Node.js reports an unhandled rejection here
await Promise.allSettled([risky]);To fix it, put both promises into a single call: await Promise.allSettled([fails(), slow()]).
When to choose allSettled
Use allSettled when:
- The tasks are independent, so one failure shouldn't throw away the others.
- You need a full report, such as a count of successes and failures or a retry list of the failed items.
- You want a cleanup step to run only after every operation has finished, including the ones that failed.
Prefer Promise.all when one failure makes the whole result useless. With all, your code can react to the problem right away instead of waiting for the slowest task.
Exercise
You call await Promise.allSettled([delay(200, 'a'), delay(20, 'b', true), 'c']) with the delay helper from this chapter. About how long does it take, and what is the array of status values?
Show answer
About 200 ms, because allSettled waits for the slowest input even though one input rejects at 20 ms. The statuses are ['fulfilled', 'rejected', 'fulfilled']. The plain value 'c' counts as already fulfilled, and the results follow input order.
Exercise
A teammate writes try { const r = await Promise.allSettled(tasks); render(r.map(o => o.value)); } catch (e) { showError(e); } and says failures will appear through showError. What is wrong, and how would you fix it?
Show answer
Input rejections never reach the catch block, because allSettled fulfills even when inputs reject. Each failure becomes undefined in r.map(o => o.value) and gets rendered silently. Check o.status for each result: render o.value for 'fulfilled' results, and pass o.reason to showError or a failure list for 'rejected' results.
Exercise
Write an allSettled replacement using only Promise.all, Promise.resolve, and then.
Show answer
Map each input with Promise.resolve(item).then(value => ({ status: 'fulfilled', value }), reason => ({ status: 'rejected', reason })) and pass the resulting array to Promise.all. The rejection handler turns every rejection into a fulfilled result object, so Promise.all can never fail fast.