Last active
July 15, 2022 11:15
-
-
Save Octopixell/a88bc8a19d726ba232fa07b722e783b5 to your computer and use it in GitHub Desktop.
Named Promise.All() using Typescript (inspired by: https://stackoverflow.com/a/59703424)
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
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