Skip to content

Instantly share code, notes, and snippets.

@ferdaber
Last active July 24, 2024 18:01
Show Gist options
  • Select an option

  • Save ferdaber/caed3e205995c935f3cbdca66ac322a5 to your computer and use it in GitHub Desktop.

Select an option

Save ferdaber/caed3e205995c935f3cbdca66ac322a5 to your computer and use it in GitHub Desktop.
Resolve Promises in sequence or in parallel
/**
* 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