14.2. Fetch with a timeout and cancellation
Topics
This question is in
14. Timeouts, retries and concurrencyfetch has no time limit of its own. On a bad mobile connection a request can hang for minutes while the page shows a spinner. Rejecting a wrapper promise after a while is not enough either: the request keeps running and keeps the connection busy. The fix is to abort it, with an AbortController, and to let the caller cancel it too (the user leaves the page, a newer search replaces this one).
Write fetchWithTimeout(url, options) in fetch-with-timeout.js. It calls fetch and aborts the request when options.timeout milliseconds pass, or when the caller's options.signal aborts, whichever comes first.
Signature
function fetchWithTimeout(url, options) // returns a Promise of a Responseurl: passed tofetchunchanged.options: optional. Every optionfetchknows (method,headers,body…) is passed on, plus two of your own:timeout: the time limit in ms. Missing means no time limit.signal: anAbortSignalfrom the caller. Aborting it cancels the request.
- Returns the promise of
fetch's response, or a rejection.
Requirements
fetchis called once, at once, withurl, every other option, and anAbortSignalof your own.timeoutis not passed tofetch.- A response that arrives in time is the result.
- When
timeoutms pass first (exactly then, not earlier), the request is aborted and the result rejects with aDOMExceptionnamed"TimeoutError". - Without
timeout, no timer is started and the request may take as long as it takes. - When the caller's
signalaborts, the request is aborted and the result rejects with the signal's ownreason. - If
signalhas already aborted,fetchis not called and the result rejects withsignal.reason. - A time-out never aborts the caller's signal.
- When the request settles (response, error or abort), the timer is cleared and the listener on the caller's signal is removed. Aborting after the response changes nothing.
- An error from
fetch, including one thrown at once, comes back unchanged as a rejection. - Each call has its own controller and timer.
Examples
const response = await fetchWithTimeout("/api/user", { timeout: 3000 });
// the response, if it arrives within 3 stry {
await fetchWithTimeout("/api/report", { timeout: 2000 }); // the server takes 10 s
} catch (error) {
console.log(error.name); // "TimeoutError", at 2000 ms; the request is aborted
}const controller = new AbortController();
const request = fetchWithTimeout("/api/search?q=re", { timeout: 5000, signal: controller.signal });
controller.abort();
request.catch((error) => console.log(error.name)); // "AbortError": the caller's reasonfetchWithTimeout("/api/post", { method: "POST", body: "{}", timeout: 1000 });
// fetch("/api/post", { method: "POST", body: "{}", signal: <your signal> })Environment
- Plain JavaScript in a browser page; the tests call the global
fetchWithTimeoutfromfetch-with-timeout.js. - The page has no network: each test puts in a fake
fetchthat answers after a delay and, like the real one, rejects withsignal.reasonwhen its signal aborts. - The tests run on a virtual clock that replaces
setTimeoutandclearTimeout.AbortSignal.timeoutuses the browser's own timers, which the clock cannot move, so usesetTimeout. - Time spent reading the body after the response arrives is not part of this problem.
Hints
controller.abort(reason)takes a reason. What does the promise fromfetchreject with when its signal aborts?- The abort event fires once, when a signal aborts. What if it aborted before you started listening?
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