Skip to content

Instantly share code, notes, and snippets.

@Octopixell
Last active July 15, 2022 11:15
Show Gist options
  • Save Octopixell/a88bc8a19d726ba232fa07b722e783b5 to your computer and use it in GitHub Desktop.
Save Octopixell/a88bc8a19d726ba232fa07b722e783b5 to your computer and use it in GitHub Desktop.
Named Promise.All() using Typescript (inspired by: https://stackoverflow.com/a/59703424)
type ThenArg<T> = T extends PromiseLike<infer U> ? U : T;
export const namedPromiseAll = async <
T extends Record<string, Promise<any>>,
TResolved extends {[P in keyof T]: ThenArg<T[P]>}
>(namedPromises: T): Promise<TResolved> => {
const entries = Object.entries(namedPromises);
const results = await Promise.all(entries.map(e => e[1]));
const namedResults: TResolved = <TResolved>{};
for (let i = 0; i < results.length; ++i) {
const name: keyof T = entries[i][0];
namedResults[name] = results[i];
}
return namedResults;
};
// Can be used as follows:
const results = await namedPromiseAll({
somePromise: Promise.resolve([]),
anotherPromise: Promise.resolve(true),
});
// Which then allows you to reference the promises by name:
console.log(results.anotherPromise);
// Or simply destructure your promises and use them like so:
const { somePromise, anotherPromise } = await namedPromiseAll({
somePromise: Promise.resolve([]),
anotherPromise: Promise.resolve(true),
});
console.log(anotherPromise);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment