Promise.race
| First settles wins | |
| Race a timeout | |
| Any success (Promise.any) | |
| When racing helps |
First settles wins
Promise dot race takes several promises and mirrors the first one that settles. Settle means fulfill or reject, whichever happens first. The losers keep running, but their results are ignored.
const fast: Promise<string> = Promise.resolve("fast");
const slow: Promise<string> = new Promise((resolve) => {
setTimeout(() => resolve("slow"), 500);
});
const win: string = await Promise.race([fast, slow]);
Race a timeout
A classic use races real work against a timer that rejects. If the timer wins, the await throws a timeout error. This keeps a slow backend from freezing the program.
function withTimeout(work: Promise<string>, ms: number): Promise<string> {
const timer: Promise<string> = new Promise((_, reject) => {
setTimeout(() => reject(new Error("timeout")), ms);
});
return Promise.race([work, timer]);
}
Any success (Promise.any)
Promise dot any waits for the first fulfillment and skips rejections until one success lands. It only rejects when every input rejects. Use it to try mirrors and take the first healthy answer.
const best: string = await Promise.any([
Promise.reject(new Error("one down")),
Promise.resolve("mirror two"),
]);
console.log(best);
When racing helps
Racing fits timeouts, first mirror wins, and user cancel flows. It does not speed up work that must all finish. For full results keep all, for fastest answer keep race.
async function firstMirror(a: Promise<string>, b: Promise<string>): Promise<string> {
return Promise.race([a, b]);
}
const v = await firstMirror(Promise.resolve("a"), Promise.resolve("b"));
console.log(v);
Next: HTTPS client
Article author: Arthur Isaev