Last active
July 24, 2024 18:01
-
-
Save ferdaber/caed3e205995c935f3cbdca66ac322a5 to your computer and use it in GitHub Desktop.
Resolve Promises in sequence or in parallel
This file contains hidden or 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
| /** | |
| * Resolves a list of deferred tasks in parallel or in sequence. | |
| */ | |
| async function resolvePromises<const T extends readonly (() => any)[]>( | |
| deferreds: T, | |
| parallel?: boolean | |
| ): Promise<{ -readonly [P in keyof T]: T[P] extends () => infer R ? Awaited<R> : unknown }> { | |
| if (parallel) { | |
| return Promise.all(deferreds.map(deferred => deferred())) as any; | |
| } else { | |
| const values: Promise<any>[] = []; | |
| for (const deferred of deferreds) { | |
| values.push(await deferred()); | |
| } | |
| return values as any; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment