Sub topic 6
Typing Promise.all, allSettled, race, and any
This chapter assumes you know basic TypeScript types, union types and narrowing, simple generics, and async/await. You should also know that Promise<T> is the type of a value that arrives later. The four combinators below take several promises and return one. Each does so with a different rule for when it finishes. Each also produces a different result type.
What the combinators have in common
A combinator is a static method on Promise that takes an iterable of promises and returns a single promise. In the standard library typings, each one uses Awaited<T> on the input elements, so plain values and nested promises are unwrapped for you. All four also accept non-promise values, which are treated as already resolved.
| Combinator | Resolves when | Rejects when | Resolved type for `[Promise<A>, Promise<B>]` | Column |
|---|---|---|---|---|
| `Promise.all` | every input fulfills | any input rejects (first rejection wins) | `[A, B]` | |
| `Promise.allSettled` | every input settles | never | `[PromiseSettledResult<A>, PromiseSettledResult<B>]` | |
| `Promise.race` | the first input settles with a value | the first input to settle rejects | `A \ | B` |
| `Promise.any` | the first input fulfills | all inputs reject | `A \ | B` |
Promise.all: tuples stay tuples
Promise.all is declared roughly like this in the standard library:
// Simplified from lib.es2015.promise.d.ts
declare function all<T extends readonly unknown[] | []>(
values: T
): Promise<{ -readonly [P in keyof T]: Awaited<T[P]> }>;The | [] in the constraint is a hint to the compiler. It tells TypeScript to infer a tuple instead of an array when you pass an array literal. The mapped type then unwraps each position separately. This is why two promises of different types give you two differently typed results:
declare function getUser(id: number): Promise<{ id: number; name: string }>;
declare function getPosts(id: number): Promise<string[]>;
async function load(id: number) {
const [user, posts] = await Promise.all([getUser(id), getPosts(id)]);
return { name: user.name, count: posts.length };
}Here user is { id: number; name: string } and posts is string[]. The two requests run at the same time because both promises are created before either is awaited.
When you pass an array, you get an array
If the input is a homogeneous array, the result is an array of the unwrapped element type:
declare function getUser(id: number): Promise<{ id: number; name: string }>;
async function loadNames(ids: number[]): Promise<string[]> {
const users = await Promise.all(ids.map((id) => getUser(id)));
return users.map((u) => u.name);
}ids.map(...) has type Promise<{ id: number; name: string }>[], so users is { id: number; name: string }[]. The array can be empty, and the code still works. Promise.all([]) resolves to [].
Losing the tuple by storing the array first
A common error is to build the array in a variable first. Once it sits in a variable, TypeScript has already widened it to an array of a union, and the position information is gone:
declare function getUser(id: number): Promise<{ id: number; name: string }>;
declare function getPosts(id: number): Promise<string[]>;
async function broken(id: number) {
const pending = [getUser(id), getPosts(id)];
const [user, posts] = await Promise.all(pending);
// user: { id: number; name: string } | string[]
// posts: { id: number; name: string } | string[]
return { user, posts };
}
async function fixed(id: number) {
const pending = [getUser(id), getPosts(id)] as const;
const [user, posts] = await Promise.all(pending);
// user: { id: number; name: string }
// posts: string[]
return { user, posts };
}The as const assertion makes the array a readonly tuple. The readonly unknown[] constraint accepts it, and the -readonly in the mapped type removes the modifier from the result.
Failure behavior the types do not show
The type Promise<[A, B]> says nothing about failure. If any input rejects, the combined promise rejects with that first reason. The other inputs keep running, and their results are discarded. Rejections that happen later are still handled, so they do not trigger unhandled rejection warnings. Promise.all does not cancel anything. To stop the other work, pass an AbortSignal to each task, which a later chapter covers.
Promise.allSettled: every outcome, never rejects
When you want a result from every input even if some fail, use Promise.allSettled. Its result type is PromiseSettledResult<T>, which is a union discriminated by status:
interface PromiseFulfilledResult<T> {
status: "fulfilled";
value: T;
}
interface PromiseRejectedResult {
status: "rejected";
reason: any;
}
type PromiseSettledResult<T> =
| PromiseFulfilledResult<T>
| PromiseRejectedResult;Reading value without checking status is a compile error, because value exists only on one member of the union. Checking status narrows the type:
declare function getUser(id: number): Promise<{ id: number; name: string }>;
async function loadMany(ids: number[]): Promise<string[]> {
const results = await Promise.allSettled(ids.map((id) => getUser(id)));
const names: string[] = [];
for (const r of results) {
if (r.status === "fulfilled") {
names.push(r.value.name);
} else {
console.error(r.reason);
}
}
return names;
}Note that reason is typed any, not unknown. That is a historical choice in the library typings. Treat it as unknown yourself by assigning it to an unknown variable before use, or by narrowing it with instanceof Error. The error-handling chapter explains why.
Filtering with a type guard
Separating successes from failures is common enough to deserve helpers. A user-defined type guard lets filter change the element type:
declare function getUser(id: number): Promise<{ id: number; name: string }>;
function isFulfilled<T>(
r: PromiseSettledResult<T>
): r is PromiseFulfilledResult<T> {
return r.status === "fulfilled";
}
function isRejected<T>(
r: PromiseSettledResult<T>
): r is PromiseRejectedResult {
return r.status === "rejected";
}
async function partition(ids: number[]) {
const results = await Promise.allSettled(ids.map((id) => getUser(id)));
const users = results.filter(isFulfilled).map((r) => r.value);
const reasons: unknown[] = results.filter(isRejected).map((r) => r.reason);
return { users, reasons };
}Without the guards, results.filter((r) => r.status === "fulfilled") still returns the full union type in older compilers. TypeScript 5.5 and later can infer such a predicate for simple arrow functions, but an explicit guard works in every version and states the intent.
With a tuple input, allSettled keeps positions too. Promise.allSettled([getUser(1), getPosts(1)]) resolves to [PromiseSettledResult<{...}>, PromiseSettledResult<string[]>]. You narrow each element on its own.
Promise.race: the first one to settle
Promise.race follows whichever input settles first, whether it fulfills or rejects. Because any input might win, the resolved type is the union of all the unwrapped input types: Promise<Awaited<T[number]>>. Unlike all, position information is gone.
The classic use is a timeout. A promise that only ever rejects has type Promise<never>, and never disappears from a union:
async function fetchLength(url: string): Promise<number> {
const res = await fetch(url);
const text = await res.text();
return text.length;
}
function timeout(ms: number): Promise<never> {
return new Promise<never>((_resolve, reject) => {
setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms);
});
}
async function fetchLengthWithin(url: string, ms: number): Promise<number> {
return Promise.race([fetchLength(url), timeout(ms)]);
}The type of Promise.race([...]) is Promise<number>, because number | never is number. The type system correctly says that a successful result is a number. The timeout path shows up only as a rejection.
Two things the types do not cover:
- The slower promise is not cancelled. The
fetchabove keeps running after the timeout wins, and the timer keeps running if the fetch wins. Production code clears the timer and passes anAbortSignal. Promise.race([])never settles, and its type isPromise<never>. Check for an empty input if it can happen.
Promise.any: the first success
Promise.any ignores rejections until every input has rejected. It resolves with the first fulfilled value, and its type is also Promise<Awaited<T[number]>>. If all inputs reject, it rejects with an AggregateError, an error whose errors property holds every individual reason.
async function fetchText(url: string): Promise<string> {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP ${res.status} from ${url}`);
}
return res.text();
}
async function firstAvailable(mirrors: string[]): Promise<string> {
try {
return await Promise.any(mirrors.map((url) => fetchText(url)));
} catch (err) {
if (err instanceof AggregateError) {
const reasons: unknown[] = err.errors;
console.error(`All ${reasons.length} mirrors failed`, reasons);
}
throw err;
}
}The success type is string. The failure type is not visible in the signature, and AggregateError.errors is typed any[]. Assigning it to unknown[] forces you to narrow before using an element.
Choosing between them
Pick the combinator by asking what the caller needs when something fails.
- If one failure makes the whole result useless, use
Promise.all. The tuple form gives you precise types per position. - If partial results are acceptable, use
Promise.allSettledand narrow onstatus. - If you want the fastest answer and a failure is a valid answer, use
Promise.race, usually for a timeout. - If you want the fastest success and failures are acceptable fallbacks, use
Promise.any.
Combining them is normal. A frequent pattern is allSettled over a list of tasks, each of which internally uses race for its own timeout.
Common errors
- Awaiting inside a loop and calling it parallel.
for (const id of ids) users.push(await getUser(id))runs one request at a time.Promise.all(ids.map(getUser))starts them all together. For large lists, bound the concurrency, since all inputs start at once. - Mixing result positions after
race. Becauseracereturns a union, you often have to narrow the result, for example with akindfield on each branch. - Forgetting that
reasonisany.r.reason.messagecompiles but can throw at runtime if the rejection was not anError. - Expecting
Promise.allon an object. It takes an iterable, not a record. To resolve an object of promises, useObject.entriesandObject.fromEntries, and accept that you will lose the per-key types unless you write a mapped-type helper.
Exercise
Given declare function a(): Promise<number>; declare function b(): Promise<string>;, what is the type of x in const x = await Promise.race([a(), b()]);? What is the type of y in const [y] = await Promise.all([a(), b()]);?
Show answer
x is string | number, because race returns the union of the unwrapped element types and does not preserve positions. y is number, because Promise.all infers a tuple from the array literal and unwraps the first position separately.
Exercise
This code fails to compile at r.value. Why, and how do you fix it?
const results = await Promise.allSettled([Promise.resolve(1), Promise.reject(new Error("x"))]);
for (const r of results) {
console.log(r.value);
}
Show answer
r is a PromiseSettledResult<number>, which is a union of a fulfilled and a rejected result, and only the fulfilled member has value. Narrow first with if (r.status === "fulfilled") { console.log(r.value); }, and handle the other branch through r.reason.
Exercise
A function calls Promise.any(urls.map(fetchText)) and wraps it in try/catch. What error type should the catch block check for when every URL fails, and what is the type of the list inside it?
Show answer
It should check err instanceof AggregateError. The list is err.errors, typed any[], so assign it to unknown[] and narrow each item before reading properties. This requires the es2021 library in tsconfig.json.