Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Created June 14, 2021 15:28
Show Gist options
  • Select an option

  • Save itsMapleLeaf/64bdc2280d184a9bdbb610e757e0a849 to your computer and use it in GitHub Desktop.

Select an option

Save itsMapleLeaf/64bdc2280d184a9bdbb610e757e0a849 to your computer and use it in GitHub Desktop.
await object
type Await<T> = T extends Promise<infer V> ? Await<V> : T
type AwaitObject<Promises extends Record<string, Promise<unknown>>> = {
[K in keyof Promises]: Await<Promises[K]>
}
async function awaitObject<Promises extends Record<string, Promise<unknown>>>(
promises: Promises,
) {
const pairs = await Promise.all(
Object.entries(promises).map(
async ([key, promise]) => [key, await promise] as const,
),
)
return Object.fromEntries(pairs) as AwaitObject<Promises>
}
const result = await awaitObject({
a: Promise.resolve("test"),
b: Promise.resolve(123),
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment