Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import * as assert from 'assert/strict';
async function forkJoin(objOrArrOfPromises) {
let promises;
if (Array.isArray(objOrArrOfPromises)) {
promises = objOrArrOfPromises;
} else {
promises = Object.values(objOrArrOfPromises);
}
const settled = await Promise.allSettled(promises);
if (settled.some((p) => p.status === 'rejected')) {
const reasons = settled.flatMap(
(p) => p.status === 'rejected' ? [p.reason] : []);
throw new AggregateError(reasons, 'One or more Promises were rejected');
}
// All Promises were fulfilled
const values = settled.flatMap(
(p) => p.status === 'fulfilled' ? [p.value] : []);
if (Array.isArray(objOrArrOfPromises)) {
return values;
} else {
const keys = Object.keys(objOrArrOfPromises);
return Object.fromEntries(keys.map((key, i) => [key, values[i]]));
}
}
assert.deepEqual(
await forkJoin([Promise.resolve('a'), Promise.resolve('b'), Promise.resolve('c')]),
['a', 'b', 'c']
);
assert.deepEqual(
await forkJoin({a: Promise.resolve(1), b: Promise.resolve(2), c: Promise.resolve(3)}),
{a: 1, b: 2, c: 3}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment