Sub topic 2
Failing Fast When the Signal Is Already Aborted
This chapter assumes you know promises, async/await, setTimeout, and addEventListener. It also assumes you can already create an AbortController and read signal.aborted and signal.reason.
Check Before You Start
A caller may pass a signal that is already aborted. The abort event has already fired at that point, so a listener added now will never run. Check signal.aborted first and reject with signal.reason straight away. Built-in APIs such as fetch behave the same way.
Building a Cancellable delay()
The function below wraps setTimeout in a promise. The signal is optional, so the code uses ?. everywhere it touches the signal.
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 });
});
}Cleaning Up on Both Paths
The function can end in two ways, and each one cleans up something different:
| Outcome | Cleanup |
|---|---|
| Abort | `clearTimeout` stops the timer from firing later. |
| Success | `removeEventListener` drops `onAbort`, so a long-lived signal does not keep the closure alive. |
Checkpoints in Async Loops
Code made of many await steps cannot be interrupted in the middle. Instead, call signal.throwIfAborted() at safe points. It throws signal.reason if the signal has been aborted.
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;
}Forwarding the Signal
In fetchAll, the same signal goes to fetch. One abort therefore stops the loop and also cancels the request that is in flight. Apply the same rule to every nested cancellable call, for example await delay(100, { signal }).
Exercise
Why does delay() check signal.aborted before adding the abort listener, instead of relying on the listener alone?
Show answer
An already-aborted signal has fired its abort event, and it will not fire it again. A listener added afterward would never run, so the promise would resolve after ms instead of rejecting at once.
Exercise
What goes wrong if delay() resolves without calling removeEventListener?
Show answer
The onAbort listener stays attached to the signal after the work finishes. With a shared, long-lived signal, these closures build up and leak memory. A later abort would also call clearTimeout and reject on a promise that has already settled.