Created
March 21, 2023 11:56
-
-
Save NuroDev/a8a526174fd8776fc3d7f5eeb4a15de9 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
/** | |
* 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