Last active
November 14, 2025 13:13
-
-
Save ratijas/e7bd9714115564509b1eed8aa8c37b56 to your computer and use it in GitHub Desktop.
JavaScript Promise.all() but using object keys
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
| /** | |
| * Just like Promise.all(), but takes and returns objects with named keys, so you don't have to use array indices. | |
| * | |
| * Creates a Promise that is resolved with an object of results when all of the provided Promises | |
| * resolve, or rejected when any Promise is rejected. | |
| * @param values An object with string keys and Promises as values. | |
| * @returns A new Promise. | |
| */ | |
| export async function allNamed<T extends { readonly [key: string]: unknown }>( | |
| values: T, | |
| ): Promise<{ -readonly [P in keyof T]: Awaited<T[P]> }> { | |
| const result = {} as { -readonly [P in keyof T]: Awaited<T[P]> }; | |
| const promises = [] as Promise<void>[]; | |
| for (const key in values) { | |
| const value = values[key]; | |
| // Use Promise.all on individual values, because we don't know whether they are Promises themselves or plain values. | |
| const promise = Promise.all([value]).then(([value]) => { | |
| result[key] = value; | |
| }); | |
| promises.push(promise); | |
| } | |
| await Promise.all(promises); | |
| return result; | |
| } | |
| // Usage example: | |
| const { | |
| // revenue, | |
| latestInvoices, | |
| cardData, | |
| } = await Promises.allNamed({ | |
| // revenue: fetchRevenue(), | |
| latestInvoices: fetchLatestInvoices(), | |
| cardData: fetchCardData(), | |
| }); | |
| // With named keys you don't have to adjust data[] indices | |
| // when toggling `revenue` like you would with Promise.all: | |
| const data = await Promise.all([ | |
| // revenuePromise, | |
| latestInvoicesPromise, | |
| cardDataPromise, | |
| ] as const); | |
| // const revenue = data[0]; | |
| const latestInvoices = data[0]; // <- not 1 anymore | |
| const { | |
| numberOfCustomers, | |
| totalPaidInvoices, | |
| totalPendingInvoices, | |
| numberOfInvoices, | |
| } = data[1]; // <- not 2 anymore |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment