Sub topic 9
Building a Timeout with Promise.race
This chapter assumes you already know how Promise.race settles with the first input that settles. It also assumes you are comfortable with async/await, try/catch/finally, and setTimeout.
A timeout is the most common use of Promise.race. You race the real operation against a promise that rejects after a fixed delay. If the operation settles first, you get its result or its error. If the delay runs out first, you get a timeout error.
The Timeout Helper
async function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms);
});
try {
return await Promise.race([promise, timeout]);
} finally {
clearTimeout(timer);
}
}Here is what each part does:
timeoutnever fulfills. Its only job is to reject oncemsmilliseconds have passed.timeris declared outside the executor so that thefinallyblock can reach it. The executor runs synchronously, sotimeris assigned beforePromise.raceis called.awaitinsidetrymatters. If you wrotereturn Promise.race(...)withoutawait, thefinallyblock would run right away, before the race settles. The timer would be cleared too early and the timeout would never fire.finallyclears the timer whichever way the race ends: success, failure of the operation, or the timeout itself.
Using It
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function main() {
console.log(await withTimeout(delay(50, 'fast'), 200)); // 'fast'
try {
await withTimeout(delay(500, 'slow'), 200);
} catch (err) {
console.log(err.message); // 'Timed out after 200 ms'
}
}
main();Why Clearing the Timer Matters
If you skip clearTimeout, the race still gives the right answer, but the timer stays scheduled. In Node.js a pending timer keeps the process alive, so a script that finished its work in 50 ms would sit idle until a 30-second timeout ran out. In a server that wraps thousands of requests, every leftover timer is also memory and work that has no purpose.
The late rejection from an uncleared timer does not cause an unhandled rejection error. Promise.race already attached a handler to timeout, so the rejection is quietly ignored.
Common Mistakes
| Mistake | Effect |
|---|---|
| `return Promise.race(...)` without `await` in `try` | `finally` clears the timer immediately, so the timeout never fires |
| No `clearTimeout` | Timer outlives the race and keeps Node.js processes running |
| Creating the timer outside the helper and reusing it | One timeout shared across calls fires at the wrong time |
| Treating every error as a timeout | The operation's own rejection also comes through the race. Check the error before you report a timeout |
To tell a timeout apart from the operation's own errors, reject with a dedicated error type, such as a TimeoutError class that extends Error, and check it with instanceof.
Exercise
A teammate rewrites the helper body as try { return Promise.race([promise, timeout]); } finally { clearTimeout(timer); }. They call withTimeout(delay(500, 'slow'), 200). What happens, and why?
Show answer
The call resolves to 'slow' after about 500 ms, and no timeout error is thrown. Without await, the try block returns the race promise right away, so finally runs immediately and clears the timer before it can fire. The timeout promise then never settles, and the race simply waits for the operation.
Exercise
Why is timer declared with let outside the new Promise executor instead of inside it?
Show answer
The finally block needs the timer ID to call clearTimeout. A variable declared inside the executor would be out of scope there. The executor runs synchronously during new Promise, so timer already holds the ID when the race starts.