Promises
Utilities for working with promises.
promiseMap
Takes an object of promises and resolves them in parallel, returning an object with the same keys and resolved values. A more ergonomic alternative to Promise.all with array destructuring.
import { promiseMap } from '@repo/utils'
function promiseMap<T extends Record<string, unknown>>(
input: { [K in keyof T]: MaybePromise<T[K]> }
): Promise<T>
Example
import { promiseMap } from '@repo/utils'
// Instead of:
const [user, posts, settings] = await Promise.all([
fetchUser(id),
fetchPosts(id),
fetchSettings(id),
])
// Write:
const { user, posts, settings } = await promiseMap({
user: fetchUser(id),
posts: fetchPosts(id),
settings: fetchSettings(id),
})
Works with mixed promise and non-promise values:
import { promiseMap } from '@repo/utils'
const result = await promiseMap({
data: fetchData(), // Promise
label: 'static value', // plain value
})
// result.data -- resolved value
// result.label -- 'static value'
isPromise
Checks if a value is a Promise by verifying it has .then() and .catch() methods.
import { isPromise } from '@repo/utils'
function isPromise(value: unknown): boolean
Example
import { isPromise } from '@repo/utils'
isPromise(Promise.resolve(42)) // true
isPromise(fetch('/api')) // true
isPromise(42) // false
isPromise(null) // false
isPromise({ then: () => {} }) // false (missing .catch)