Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
14.1. Reject a promise after a time limit
Easy
Topics
This question is in
14. Timeouts, retries and concurrencyA page waits for a promise: a request, a script loading, a worker answering. If that promise never settles, the spinner turns forever. A time limit turns "never" into a clear failure the page can handle: show an error, offer a retry, fall back to cached data.
Write withTimeout(promise, ms) in timeout.js. It returns a new promise that settles the way promise does if promise settles within ms milliseconds. If ms pass first, it rejects with an error named TimeoutError.
Signature
function withTimeout(promise, ms) // returns a Promisepromise: the work to wait for. A plain value (not a promise) counts as already finished.ms: the time limit in milliseconds.- Returns a promise that fulfills with the promise's value, rejects with the promise's error, or rejects with a
TimeoutError.
Requirements
withTimeoutreturns a promise.- If
promisefulfills within the limit, the result fulfills with the same value, as soon aspromisedoes. - If
promiserejects within the limit, the result rejects with the same error object. - If
mspass first, the result rejects at exactlyms, not earlier, with anErrorwhosenameis"TimeoutError"and whose message includesms. - Once the result has settled, a later outcome of
promisechanges nothing, and a late rejection is not reported as unhandled. - The timer is cleared as soon as
promisesettles, whether it fulfilled or rejected. - A plain value, or a promise that has already resolved, wins even against a 0 ms limit.
- Each call has its own timer.
Examples
const slow = new Promise((resolve) => setTimeout(() => resolve("data"), 500));
withTimeout(slow, 1000).then(console.log);
// at 500 ms: "data"
withTimeout(slow, 200).catch((error) => console.log(error.name, error.message));
// at 200 ms: "TimeoutError" "Timed out after 200 ms"withTimeout(Promise.reject(new TypeError("bad")), 100).catch((error) => console.log(error.name));
// at once: "TypeError" (the promise's own error)withTimeout(42, 0).then(console.log);
// 42: a plain value is already done, so the 0 ms timer never winsEnvironment
- Plain JavaScript in a browser page; the tests call the global
withTimeoutfromtimeout.js. - The tests run on a virtual clock that replaces
setTimeoutandclearTimeout, so use those. - Stopping the slow work itself is not part of this problem (a promise cannot be cancelled from outside): that is problem 14.2, with
fetchandAbortController. - The wording of the message is up to you, as long as it includes
ms.
Hints
- Which kind of race needs two contestants: the promise, and what else?
- A promise can only settle once. Does that mean you can call
resolveandrejectwithout checking who came first?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…