Promise.allSettled Partial Failure Handling
Collect every outcome with Promise.allSettled when a batch must not fail as a whole, then branch on fulfilled versus rejected.
Code
async function fetchOne(id) {
if (id % 3 === 0) throw new Error('upstream 500 for ' + id);
return { id, value: id * 10 };
}
async function collect(ids) {
// allSettled:始终等到全部落地,单点失败不连坐
const results = await Promise.allSettled(ids.map(fetchOne));
const ok = [];
const failed = [];
results.forEach((result, index) => {
if (result.status === 'fulfilled') ok.push(result.value);
else failed.push({ id: ids[index], reason: result.reason.message });
});
return { ok, failed };
}
collect([1, 2, 3, 4, 5, 6]).then((summary) => {
console.log('ok:', summary.ok.length, 'failed:', summary.failed.length);
console.log(summary.failed);
});Output
Captured from a sandboxed run of this snippet in the build pipeline.
ok: 4 failed: 2
[
{ id: 3, reason: 'upstream 500 for 3' },
{ id: 6, reason: 'upstream 500 for 6' }
]How the snippet works
Count the functions fetchOne and collect as the entire surface area of Promise.allSettled Partial Failure Handling.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The code refuses to proceed on bad state and throws Error at its guard.
The result comes back as an object carrying id.
What to watch for
- The guard
id % 3 === 0aborts the flow through an earlythrowwhen its condition holds.
Applying it
The main signature reads async function fetchOne(id)
The demo output is labeled (ok:), so every printed line maps back to its originating operation.
The call returns id.
Statements that matter
const results = await Promise.allSettled(ids.map(fetchOne));
collect([1, 2, 3, 4, 5, 6]).then((summary) => {
console.log('ok:', summary.ok.length, 'failed:', summary.failed.length);
console.log(summary.failed);
});
if (id % 3 === 0) throw new Error('upstream 500 for ' + id);
Interactive Tools for This Topic
FAQ
- Does `fetchOne` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- What happens if the preconditions do not hold?
- The code throws `Error` — the guard `id % 3 === 0` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `fetchOne`, `collect` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.