In this article
A timeout that rejects a promise can leave the request running. Review whether the signal reaches fetch, whether the deadline covers the response body, and whether the timer is cleared on every exit. Test those three behaviors separately before accepting a generated wrapper.
Specify what a timeout must stop
Consider an illustrative helper that retrieves a small JSON document. The requested behavior is to return parsed JSON, reject HTTP failures, and request cancellation if a configured timeout expires before reading the body finishes. The helper owns one request and one timer. It does not retry, update application state, or merge a caller cancellation signal. Narrowing that contract makes the important review question visible: which operation actually receives the cancellation?
An assistant may generate a race between fetch and a rejecting timer. That can stop the caller waiting, but Promise.race settles its result without canceling the losing operation. Treat rejection and cancellation as separate observations in the review. A test that checks only the displayed error cannot tell whether the request is still consuming resources in the background. MDN: Promise.race semantics
Prove that losing the race does not stop work
Run this original example as a JavaScript module in Node.js. It uses manually controlled promises rather than a real network request, so the order is explicit: the deadline rejects first, the caller observes that failure, and the work still completes afterward. The completed counter is the independent observation. The example demonstrates promise behavior; it is not a measurement of network load or a claim about a particular server.
This is a useful counterexample to include in a coding prompt. Ask the assistant to connect the timeout to the underlying operation and preserve the existing success and error results. Do not ask it merely to make the error appear faster. That narrower request is already satisfied by the flawed race. Make the acceptance condition include the signal and timer ownership, so the repair must address the missing behavior.
import assert from "node:assert/strict";
let finishWork;
let expire;
let completed = 0;
const work = new Promise(resolve => { finishWork = resolve; })
.then(() => { completed += 1; });
const deadline = new Promise((_, reject) => { expire = reject; });
const raced = Promise.race([work, deadline]);
const rejected = assert.rejects(raced, /deadline/);
expire(new Error("deadline"));
await rejected;
assert.equal(completed, 0);
finishWork();
await work;
assert.equal(completed, 1);
Keep cancellation active until the body is consumed
Fetch accepts a signal, and its response promise can resolve before the full response body arrives. Body reading is asynchronous and can also be aborted. Therefore, this wrapper awaits response.json inside the try block instead of returning its promise immediately. Clearing the timer after headers would leave a slow body outside the intended timeout. The explicit ok check handles HTTP failures, which fetch does not automatically turn into promise rejections. MDN: Using Fetch and canceling a request
The controller receives a named timeout error as its abort reason; abort accepts an explicit reason. A finally block releases the timer after success, request failure, body failure, or timeout. The injected fetch and timer functions are test seams, with the platform functions as defaults. This example accepts positive integer millisecond values up to 2,147,483,647; the range is a deliberate wrapper policy rather than a promise to support every possible scheduling duration. MDN: AbortController.abort and its reason
async function getJson(url, timeoutMs, {
fetchImpl = fetch, arm = setTimeout, disarm = clearTimeout,
} = {}) {
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647) {
throw new RangeError("invalid timeout");
}
const controller = new AbortController();
const timer = arm(() => {
controller.abort(new DOMException("Request timed out", "TimeoutError"));
}, timeoutMs);
try {
const response = await fetchImpl(url, { signal: controller.signal });
if (!response.ok) throw new Error("HTTP " + response.status);
return await response.json();
} finally {
disarm(timer);
}
}
Exercise pending headers and a pending body separately
Append the wrapper and this block to the first example. The manual clock exposes the scheduled callback, and the fake request rejects only when its signal is aborted. In the headers case, fetch itself remains pending. In the body case, fetch resolves, json announces that consumption has started, and only then does the test fire the deadline. Neither test waits for an arbitrary number of real milliseconds.
These observations catch two different omissions. Passing no signal breaks cancellation before headers. Returning the body promise without awaiting it clears the timer before the body test can fire it. The success, HTTP-error, and malformed-body cases also check cleanup. Keeping these cases in the same runnable file makes it possible to evaluate a generated revision against the exact same contract instead of accepting a new set of tests tailored to the revision.
function manualClock() {
let callback;
let clears = 0;
return {
arm(fn) { callback = fn; return 1; },
disarm() { callback = undefined; clears += 1; },
fire() { assert.equal(typeof callback, "function"); callback(); },
get clears() { return clears; },
};
}
function untilAborted(signal) {
return new Promise((_, reject) => {
if (signal.aborted) reject(signal.reason);
else signal.addEventListener("abort", () => reject(signal.reason), { once: true });
});
}
for (const phase of ["headers", "body"]) {
const clock = manualClock();
let seenSignal;
let bodyEntered;
const bodyReady = new Promise(resolve => { bodyEntered = resolve; });
const fetchImpl = async (_, { signal }) => {
seenSignal = signal;
if (phase === "headers") return untilAborted(signal);
return { ok: true, json() { bodyEntered(); return untilAborted(signal); } };
};
const result = getJson("/fixture", 100, { ...clock, fetchImpl });
const rejected = assert.rejects(result, { name: "TimeoutError" });
if (phase === "body") await bodyReady;
clock.fire();
await rejected;
assert.equal(seenSignal.aborted, true);
assert.equal(clock.clears, 1);
}
const cases = [
{ response: { ok: true, json: async () => ({ ready: true }) } },
{ response: { ok: false, status: 503 }, error: /HTTP 503/ },
{ response: { ok: true, json: async () => { throw new SyntaxError("bad JSON"); } },
error: { name: "SyntaxError" } },
];
for (const item of cases) {
const clock = manualClock();
const result = getJson("/fixture", 100, {
...clock, fetchImpl: async () => item.response,
});
if (item.error) await assert.rejects(result, item.error);
else assert.deepEqual(await result, { ready: true });
assert.equal(clock.clears, 1);
}
await assert.rejects(getJson("/fixture", 0), RangeError);
console.log("Race, cancellation phases, cleanup, and input checks passed.");
Preserve the error that explains the failure
Avoid a broad catch that converts every failure into a timeout. A 503 response, a JSON syntax error, and an expired deadline imply different recovery decisions. The helper leaves those distinctions visible. Its caller can decide how to present them, but should not infer that retrying is harmless merely because the request was aborted. The example is intentionally a read; write operations require their own rules for repeated effects.
When reviewing the diff, follow the controller signal from its creation to the fetch options, then follow every exit through finally. Check the successful body path as carefully as rejection. A timer left active after success can retain unnecessary work; a timer cleared before body completion stops enforcing the stated contract. Both mistakes can hide behind a passing fast-response example, which is why the controlled body case is central to this review.
Separate wrapper evidence from transport guarantees
The test double is cooperative by construction. It shows that the wrapper delivers an abort signal and retains the timeout through body consumption, but does not prove how a browser, proxy, or server releases resources. Before integrating a similar helper, exercise a controlled endpoint that sends headers and delays its body. Confirm the caller sees cancellation and that the application does not later publish stale data from another code path.
A timer callback also depends on the event loop getting a chance to run. Treat this as an application timeout, not a strict real-time guarantee. If the underlying operation ignores cancellation, this implementation cannot force it to stop. Adding caller cancellation, retries, streaming output, or shared requests changes ownership and deserves a revised contract. Keep those additions explicit so the small helper does not accumulate promises its tests never examine.
Common questions about generated timeout helpers
Is Promise.race always wrong for a timeout? No. It can express a limit on how long a caller waits when that is the intended contract. The mistake is claiming that the race cancels work by itself. If cancellation matters, identify the underlying API that supports it and verify the signal reaches that API.
Does abort undo a server action? This helper makes no such guarantee. A server may already have processed a request before the client stops waiting. Why not return the Response directly? This contract includes JSON body consumption. A helper that returns a Response transfers body ownership to its caller and needs a different policy for how long its cancellation mechanism remains active.
Sources & editorial notes
This article was authored with AI using primary-source research and an automated technical review. It has not been reviewed by a human. Code examples are illustrative; run and verify them in your own environment.
- MDN: Promise.race semantics
Checked November 29, 2026. Documents race settlement and the fact that losing operations are not automatically canceled.
- MDN: Using Fetch and canceling a request
Checked November 29, 2026. Supports signal propagation, asynchronous body consumption, and explicit HTTP status handling.
- MDN: AbortController.abort and its reason
Checked November 29, 2026. Documents aborting supported operations and supplying an explicit abort reason.
Put the reading into practice
Work through an existing repository, review AI suggestions, and test the decisions behind your changes.
Explore practice problems