Skip to content

Instantly share code, notes, and snippets.

@NuroDev
Created March 21, 2023 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NuroDev/a8a526174fd8776fc3d7f5eeb4a15de9 to your computer and use it in GitHub Desktop.
Save NuroDev/a8a526174fd8776fc3d7f5eeb4a15de9 to your computer and use it in GitHub Desktop.
/**
* Creates a promise that is resolved with a disctionary of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
*
* This function is derived from the standard `Promise.all` function, but it works with a dictionary
* of promises instead of an array.
*
* @param values A dictionary of Promises.
*
* @example
* ```ts
* const { a, b, c } = await allEntries({
* a: Promise.resolve(1),
* b: Promise.resolve(2),
* c: Promise.resolve(3),
* });
* ```
*
* @returns A new Promise that is resolved with a dictionary of results.
*/
export async function allEntries<T extends Record<string, unknown>>(
values: T
): Promise<{
[K in keyof T]: T[K] extends () => Promise<infer U> ? U : Awaited<T[K]>;
}> {
const entries = await Promise.all(
Object.entries(values).map(([key, value]) =>
Promise.resolve(value).then((res) => [key, res])
)
);
return Object.fromEntries(entries) as {
[K in keyof T]: T[K] extends () => Promise<infer U> ? U : Awaited<T[K]>;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment