Promise.all
| Wait for all | |
| One rejects | |
| Settled report | |
| Map then all |
Wait for all
Promise dot all takes a list of promises and fulfills with a list of values in the same order. All the inputs run at the same time. Await the single combined promise to get every result together.
async function loadTwo(): Promise<void> {
const vals: number[] = await Promise.all([
Promise.resolve(1),
Promise.resolve(2),
]);
console.log(vals);
}
One rejects
If any input rejects, the whole all call rejects right away. Other inputs keep running in the background, but their values are dropped. Wrap the await in try and catch when any failure must be handled.
async function demoFail(): Promise<void> {
try {
await Promise.all([
Promise.resolve(1),
Promise.reject(new Error("bad")),
]);
} catch (err: unknown) {
console.log(err);
}
}
Settled report
When every outcome matters, use allSettled instead of all. It never rejects for input failures. The result list tells for each slot whether it fulfilled or rejected.
async function report(): Promise<void> {
const out = await Promise.allSettled([
Promise.resolve(1),
Promise.reject(new Error("bad")),
]);
console.log(out.length);
}
Map then all
A common pattern maps a list of inputs to a list of promises, then awaits all at once. Map starts every task, all collects the answers. The values keep the same order as the inputs.
async function double(n: number): Promise<number> {
return n * 2;
}
const ids: number[] = [1, 2, 3];
const vals: number[] = await Promise.all(ids.map(double));
Next: Promise.race
Article author: Arthur Isaev