Sub topic 10
Passing the Signal Down to fetch and Nested Calls
This chapter assumes you know async/await and fetch, and that you have read the earlier chapters on the signal option and on throwIfAborted(). Its subject is propagation: when your function calls other cancellable functions, it passes the caller's signal down to them so that a single abort reaches every level.
Why forwarding matters
A checkpoint such as signal.throwIfAborted() runs only between steps. If your function is stuck inside await fetch(url) for ten seconds, the checkpoint can't fire until that request ends. To stop the request itself, give fetch the same signal.
async function fetchAll(urls, { signal } = {}) {
const results = [];
for (const url of urls) {
signal?.throwIfAborted();
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
results.push(await response.json());
}
return results;
}The loop uses the signal in two places. throwIfAborted() stops new iterations from starting. fetch(url, { signal }) cancels the request that is already in flight. The signal also covers response.json(), because aborting after the headers arrive cancels the body stream and makes json() reject.
Forwarding through your own layers
The same rule applies to your own helpers. Every function that accepts a signal should hand it to every cancellable thing it calls. This retry helper forwards the signal to fetch and to Node's promise-based timer, which also accepts a signal option:
import { setTimeout as sleep } from 'node:timers/promises';
async function fetchWithRetry(url, { signal, retries = 3 } = {}) {
for (let attempt = 1; ; attempt++) {
try {
const response = await fetch(url, { signal });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (err) {
if (signal?.aborted || attempt >= retries) throw err;
await sleep(500 * attempt, undefined, { signal });
}
}
}
const controller = new AbortController();
setTimeout(() => controller.abort(), 200);
fetchWithRetry('https://example.com/data.json', { signal: controller.signal })
.catch((err) => console.log(err.name)); // "AbortError"The abort can land while a request is running or while the helper waits between retries. In both cases the helper rejects promptly. The signal?.aborted check in catch matters: without it, the helper would treat a cancellation as a failed attempt and retry.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Not passing `signal` to an inner call | Abort "works" but the request keeps running | Forward `{ signal }` to every cancellable callee |
| Creating a new `AbortController` per layer | The caller's abort never reaches inner work | Reuse the caller's signal, or combine signals (covered later) |
| Retrying or swallowing errors in `catch` | Cancelled work restarts | Check `signal?.aborted` and rethrow |
| Passing `controller` instead of `controller.signal` | Callee can abort the caller's other work | Pass only the signal, which can be observed but not triggered |
Exercise
A function loadProfile(id, { signal }) calls fetch(/users/${id}) without passing the signal, then calls signal?.throwIfAborted() after the response arrives. The caller aborts 100 ms into a 3-second request. What happens, and how do you fix it?
Show answer
The request keeps running for the full 3 seconds. Then throwIfAborted() throws, so the caller still gets a rejection, but only after the network work has completed and been thrown away. Pass the signal with fetch(/users/${id}, { signal }) so the request is cancelled at 100 ms and the promise rejects right away.
Exercise
In fetchWithRetry, why is signal?.aborted checked inside the catch block?
Show answer
An aborted fetch or sleep throws into the same catch as a network failure. Without the check, the helper would count the cancellation as a failed attempt and start a new request or wait again, which defeats the abort.