Code Snippets
/

Partition allSettled Results

Partition allSettled Results

`Promise.allSettled` is the right call for partial-success workflows, but its `{ status, value, reason }` shape is awkward to consume directly. This snippet wraps it with a partitioner that returns `{ values, errors }` so the happy path stays simple, then layers in input-aware error reports that pair each failure with the original argument. Use it for fan-out fetches, batched writes, or any spot where one bad item should not poison the whole batch.

JavaScript
Medium
3 snippets
async-programming
promises
utility
error-handling

622 views

20

async function partitionSettled(promises) {
    const settled = await Promise.allSettled(promises);
    const values = [];
    const errors = [];
    for (const r of settled) {
        if (r.status === 'fulfilled') values.push(r.value);
        else errors.push(r.reason);
    }
    return { values, errors };
}

const tasks = [
    Promise.resolve(1),
    Promise.reject(new Error('boom')),
    Promise.resolve(3),
];
partitionSettled(tasks).then((r) => console.log(r));

Promise.allSettled always resolves, never throws, so wrapping it in a tiny partitioner gives the rest of your code a clean two-bucket result. Callers can decide whether a non-empty errors array is fatal or just a warning for the caller to log. This is the easiest way to keep a fan-out endpoint partially useful when one downstream service is flaky. Time complexity is O(n) over the settled array; memory is one entry per input.