Sub topic 6
Typing `Promise.all`, `allSettled`, `race`, and `any`
Assume you know basic TypeScript types, generics, promises, async/await, union types, and type narrowing. This chapter focuses on how TypeScript infers the results of promise combinators, which combine several asynchronous operations.
`Promise.all`: require every operation
Promise.all takes an iterable of promises and returns one promise. It fulfills when every input fulfills. Its result keeps the input order, even when the operations finish in a different order.
When TypeScript receives an array or tuple of promises, it derives the resolved type for each position.
async function getUser(): Promise<{ id: number; name: string }> {
return { id: 7, name: "Mina" };
}
async function getPosts(): Promise<string[]> {
return ["intro", "advanced"];
}
async function loadProfile() {
const [user, posts] = await Promise.all([getUser(), getPosts()]);
return {
displayName: user.name,
postCount: posts.length,
};
}The type of user is { id: number; name: string }, and the type of posts is string[]. The returned object has type { displayName: string; postCount: number }.
If any input rejects, Promise.all rejects. Use it when the whole result is useful only if every part succeeds.
`Promise.allSettled`: inspect every outcome
Promise.allSettled waits for every input, whether it fulfills or rejects. Its promise always fulfills with an array of settled result objects.
Each result is a discriminated union. The status property tells TypeScript which other property is available:
- A fulfilled result has
status: "fulfilled"andvalue. - A rejected result has
status: "rejected"andreason.
async function getUser(id: number): Promise<{ id: number; name: string }> {
if (id < 0) {
throw new Error("Invalid user ID");
}
return { id, name: `User ${id}` };
}
async function loadNames(ids: number[]): Promise<string[]> {
const results = await Promise.allSettled(ids.map(getUser));
const names: string[] = [];
for (const result of results) {
if (result.status === "fulfilled") {
names.push(result.value.name);
} else {
console.error("User failed:", result.reason);
}
}
return names;
}The narrowing check prevents access to value on a rejected result. It also prevents access to reason on a fulfilled result.
`Promise.race`: use the first settled result
Promise.race settles as soon as its first input settles. “Settles” includes both fulfillment and rejection. Its resolved type is a union of all possible fulfillment values.
const result = await Promise.race([
Promise.resolve(42),
Promise.resolve("ready"),
]);
// result: number | stringIf the first settled promise rejects, the race rejects, even if another input would later fulfill. A common use is applying a timeout to another operation. Remember that racing does not automatically cancel the slower operation.
`Promise.any`: use the first fulfillment
Promise.any fulfills when the first input fulfills. Its value is a union of the possible fulfillment values. It ignores rejections unless every input rejects.
If every input rejects, Promise.any rejects with an AggregateError. The error contains the individual failures in its errors property.
async function firstAvailable(): Promise<string> {
try {
return await Promise.any([
Promise.reject(new Error("Primary unavailable")),
Promise.resolve("Backup response"),
]);
} catch (error: unknown) {
if (error instanceof AggregateError) {
console.error(error.errors);
}
throw error;
}
}Choose any when one successful source is enough, such as trying several mirrors. Choose race when the earliest outcome matters, including an early failure.
Choosing a combinator
| Combinator | Finishes when | Rejection behavior | Result |
|---|---|---|---|
| `Promise.all` | Every input fulfills | Rejects when an input rejects | Tuple of values |
| `Promise.allSettled` | Every input settles | Never rejects because of an input | Array of status unions |
| `Promise.race` | One input settles | Rejects if the first settled input rejects | Union of values |
| `Promise.any` | One input fulfills | Rejects only when all inputs reject | Union of values |
Exercise
What is the type of value after const value = await Promise.race([Promise.resolve(1), Promise.resolve(false)])?
Show answer
number | boolean, because either promise can provide the first fulfilled value. The race can also reject if the first settled promise rejects.
Exercise
Which combinator should you use to collect both successful and failed results from five independent requests?
Show answer
Use Promise.allSettled. It waits for every request and returns a discriminated result for each one.