Promise.allSettled Splits Fulfilled From Rejected

Run a batch of lookups with Promise.allSettled and partition fulfilled values from rejected reasons, so one failing item does not discard the rest of the batch.

JavascriptResilience

Code

javascriptsnippet
22 lines
// Promise.allSettled: 等整个批次结束,再把成功与失败分开
const loadUser = (id) =>
  id === 3
    ? Promise.reject(new Error(`user ${id} not found`))
    : Promise.resolve(`#${id} user-${id}`);

function partition(settled) {
  const values = settled
    .filter((result) => result.status === 'fulfilled')
    .map((result) => result.value);
  const reasons = settled
    .filter((result) => result.status === 'rejected')
    .map((result) => result.reason.message);
  return { values, reasons };
}

const ids = [1, 2, 3, 4];
const settled = await Promise.allSettled(ids.map((id) => loadUser(id)));
const { values, reasons } = partition(settled);

console.log(`fulfilled ${values.length}: ${values.join(', ')}`);
console.log(`rejected ${reasons.length}: ${reasons.join(' | ')}`);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

fulfilled 3: #1 user-1, #2 user-2, #4 user-4
rejected 1: user 3 not found

Inside the snippet

Promise.allSettled Splits Fulfilled From Rejected comes down to the functions loadUser and partition.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

The result comes back as an object carrying values.

Putting it to use

Entry signature: const loadUser = (id)

Look for the fulfilled $, rejected $ prefixes when the file runs; they tie each line to its step.

The call returns values.

Core lines

const settled = await Promise.allSettled(ids.map((id) => loadUser(id)));
? Promise.reject(new Error(`user ${id} not found`))
: Promise.resolve(`#${id} user-${id}`);
.map((result) => result.reason.message);

Interactive Tools for This Topic

FAQ

Does `loadUser` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `loadUser`, `partition` at load time.