Created
June 17, 2021 17:28
-
-
Save rauschma/bdc56a046b18528959ad1db3eed05386 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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