Sub topic 10
Passing the Signal Down to fetch and Nested Calls
This chapter assumes you can already write a function that accepts { signal } = {} in its options object, check signal.aborted at the start, and add cancellation checkpoints with signal.throwIfAborted(). It also assumes you know how fetch and async/await work.
A cancellable function only works if the signal reaches the code that holds the resources: the open network connection, the pending timer, the file handle. If your function stops checking the signal but a fetch underneath keeps downloading, the caller's abort() has not really cancelled anything. This chapter covers how to pass one signal through every layer of your code.
The Rule: Every Layer Forwards the Same Signal
Each function that accepts a signal should pass that same object to every cancellable operation it starts. You don't need a new controller and you don't need to translate the signal into something else. The caller owns the controller. Every function below it only reads and forwards the signal.
Because one signal object reaches every layer, a single abort() reaches every leaf operation. The rejection then travels back up through the normal promise chain. You don't write any extra wiring for that part.
Forwarding to fetch
fetch accepts a signal in its init object. When the signal aborts, fetch cancels the request and rejects with signal.reason. With no custom reason, that is a DOMException named "AbortError". If the signal is already aborted when you call fetch, it rejects immediately and sends nothing.
The signal keeps covering the response after the headers arrive. If the abort happens while you are reading the body with response.json(), response.text(), or a stream reader, that read rejects too. That makes this pattern safe:
async function fetchJson(url, { signal } = {}) {
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json(); // also aborts if the signal fires mid-body
}You don't need a throwIfAborted() call between fetch and response.json(). Both steps already watch the signal.
Forwarding Through Nested Functions
Real code is layered. The example below shows a retry helper that waits between attempts and a higher-level function that calls it twice. Each layer forwards signal, and neither layer has to know who created it.
function delay(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const onAbort = () => {
clearTimeout(timerId);
reject(signal.reason);
};
const timerId = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve();
}, ms);
signal?.addEventListener('abort', onAbort, { once: true });
});
}
async function fetchWithRetry(url, { signal, retries = 3, backoffMs = 500 } = {}) {
for (let attempt = 0; ; attempt++) {
signal?.throwIfAborted();
try {
const response = await fetch(url, { signal });
if (response.ok) return await response.json();
if (response.status < 500 || attempt >= retries) {
throw new Error(`Request failed: ${response.status}`);
}
} catch (err) {
// Never retry a cancellation: rethrow it unchanged.
if (signal?.aborted || attempt >= retries) throw err;
}
await delay(backoffMs * 2 ** attempt, { signal });
}
}
async function loadDashboard(userId, { signal } = {}) {
const user = await fetchWithRetry(
`https://jsonplaceholder.typicode.com/users/${userId}`,
{ signal }
);
const posts = await fetchWithRetry(
`https://jsonplaceholder.typicode.com/posts?userId=${userId}`,
{ signal }
);
return { user, posts };
}
const controller = new AbortController();
loadDashboard(1, { signal: controller.signal })
.then(({ user, posts }) => console.log(user.name, posts.length))
.catch((err) => console.log('stopped:', err.name));
setTimeout(() => controller.abort(), 50);Here is what happens at each point where the abort can land:
- Inside
fetchorresponse.json(). The request rejects withsignal.reason. ThecatchinfetchWithRetryseessignal.aborted === trueand rethrows instead of retrying. - Inside
delay. The timer is cleared anddelayrejects. That rejection is outside thetry, so it propagates straight up. - Between steps. The
throwIfAborted()at the top of the loop catches it before another attempt starts.
The retry helper must check signal.aborted before deciding to retry. Without that check, an aborted request looks like a network failure and the helper retries it. The retry then fails at once because the signal is still aborted, and the loop burns through all its attempts before it gives up. Checking the signal instead of matching on err.name === 'AbortError' also works when the caller passed a custom reason.
Optional Signals Forward Cleanly
When no signal is passed, signal is undefined. Forwarding { signal: undefined } to fetch, to addEventListener, or to your own functions is fine. Each of them treats it as "not cancellable". You don't need if (signal) branches around every call. Optional chaining (signal?.throwIfAborted()) handles your own checkpoints.
Which APIs Accept a Signal
Many platform APIs accept a signal. Forward to them directly instead of wrapping them yourself.
| Environment | API | Where the signal goes |
|---|---|---|
| Browser and Node | `fetch(url, init)` | `init.signal` |
| Browser and Node | `target.addEventListener(type, fn, options)` | `options.signal` |
| Browser and Node | `readable.pipeTo(dest, options)` | `options.signal` |
| Node | `fs.promises.readFile(path, options)` | `options.signal` |
| Node | `setTimeout(ms, value, options)` from `node:timers/promises` | `options.signal` |
| Node | `events.once(emitter, name, options)` | `options.signal` |
| Node | `child_process.spawn(cmd, args, options)` | `options.signal` |
The plain global setTimeout and setInterval do not accept a signal. You have to wrap them, as delay does. Third-party libraries vary. Many HTTP clients and database drivers accept signal, but check their documentation. Passing a signal to a function that ignores it fails silently.
Common Mistakes
Dropping the Signal on One Branch
The most common bug is a single call site that forgets { signal }. Everything looks cancellable until the abort lands during that one call, which then runs to completion. When you review a cancellable function, check every await and ask whether the awaited operation received the signal.
Creating a New Controller in Each Layer
// Broken: the caller's signal never reaches fetch.
async function fetchJsonBroken(url, { signal } = {}) {
const controller = new AbortController();
const response = await fetch(url, { signal: controller.signal });
return response.json();
}A fresh controller breaks the chain. Only create a local controller when the function needs to cancel work itself, and then link it to the caller's signal.
Fan-Out Where One Failure Should Stop the Others
Promise.all rejects as soon as one promise fails, but the other requests keep running. If those requests are now pointless, create a child controller. Abort it when the caller aborts, and also abort it yourself when one request fails:
async function fetchAllOrNothing(urls, { signal } = {}) {
signal?.throwIfAborted();
const child = new AbortController();
const onParentAbort = () => child.abort(signal.reason);
signal?.addEventListener('abort', onParentAbort, { once: true });
try {
return await Promise.all(
urls.map(async (url) => {
const response = await fetch(url, { signal: child.signal });
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
return response.json();
})
);
} catch (err) {
child.abort(err); // cancel the siblings that are still running
throw err;
} finally {
signal?.removeEventListener('abort', onParentAbort);
}
}The finally block removes the listener from the parent signal. A long-lived parent signal can outlive many calls, and without the cleanup each call would leave a listener on it. Passing signal.reason to child.abort() keeps the caller's reason intact, so the caller sees the same error it would have seen without the child controller. A later chapter shows AbortSignal.any(), which does this linking for you.
Exercise
A function calls const res = await fetch(url, { signal }); and then const data = await res.json();. The caller aborts after the headers arrive but before the body finishes downloading. What happens, and do you need a throwIfAborted() between the two lines?
Show answer
res.json() rejects with signal.reason, because the response body is tied to the same signal that was passed to fetch. No extra throwIfAborted() is needed between the two calls, since both steps already watch the signal.
Exercise
In fetchWithRetry, why does the catch block check signal?.aborted instead of only checking attempt >= retries?
Show answer
Without the check, an aborted fetch is treated as a retryable failure. The helper then waits and retries, and every retry fails at once because the signal is still aborted, until all attempts are used up. Checking signal.aborted rethrows the cancellation immediately and unchanged, and it works even when the caller used a custom abort reason.
Exercise
You wrap Promise.all over three fetches in a child AbortController linked to the caller's signal. Why must you remove the listener from the caller's signal in finally?
Show answer
The caller's signal may live much longer than this one call, for example a page-level signal shared by many operations. If the listener is not removed, every call leaves a closure attached to that signal, which leaks memory. Those closures would also call abort() on child controllers that are no longer needed.