Skip to content

Instantly share code, notes, and snippets.

@eliashussary
Last active December 31, 2020 02:21
Show Gist options
  • Save eliashussary/74bc4d8d0fd5429d4cd026f9a2b5fcf8 to your computer and use it in GitHub Desktop.
Save eliashussary/74bc4d8d0fd5429d4cd026f9a2b5fcf8 to your computer and use it in GitHub Desktop.
promiseAllMap will concurrently resolve a dictionary/map of functions returning promises using `Promise.all`
type PromiseCreator<T = any> = (() => Promise<T>) | Promise<T>;
type PromiseCreatorMap<T> = {
[P in keyof T]: PromiseCreator<T[P]>;
};
type ResolvedPromiseMap<T> = {
[P in keyof T]: T[P];
};
/**
* promiseAllMap will concurrently resolve a dictionary/map of functions returning promises using `Promise.all`
* @example
*
* const myPromiseMap = {
* foo: () => Promise.resolve("Foo"),
* bar: () => Promise.resolve("Bar")
* }
*
* const { foo, bar } = await promiseAllMap(myPromiseMap)
*/
export const promiseAllMap = async <T>(
promiseCreatorMap: PromiseCreatorMap<T>
): Promise<ResolvedPromiseMap<T>> => {
// return array of promises and
// wrap resolved value as `{ name, resolved }`
const promises = Object.entries(promiseCreatorMap).map((entry) => {
const [name, promiseCreator] = entry as [string, PromiseCreator];
let p = promiseCreator;
if (typeof promiseCreator === "function") {
p = promiseCreator();
}
return Promise.resolve(p).then((resolved) => ({
name,
resolved,
}));
});
const resolvedPromises = await Promise.all(promises);
const resolvedPromisesMap = resolvedPromises.reduce(
(acc, { name, resolved }) => {
acc[name] = resolved;
return acc;
},
{}
) as ResolvedPromiseMap<T>;
return resolvedPromisesMap;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment