Sub topic 7
Building a Cancellable Promise: A Cancellable delay()
This chapter assumes you know how promises are constructed with new Promise((resolve, reject) => ...), how setTimeout and clearTimeout work, and the material from earlier chapters: signal.aborted, signal.reason, the abort event, and the early-abort check.
Many asynchronous tasks don't return promises at all. Timers, callback APIs and event emitters fall into this group. To make that kind of work cancellable, wrap it in a promise and connect the signal to that promise's reject function. A delay() function is the smallest useful example.
The working model
A cancellable promise wrapper has three parts:
- Fail fast. If the signal is already aborted, reject with
signal.reasonand start no work. - Start the work. For
delay(), the work is a timer that callsresolvewhen it fires. - Listen for abort. When the signal aborts, stop the work and reject with
signal.reason.
Whichever of the timer and the abort happens first settles the promise. A promise settles only once, so a later call to resolve or reject is ignored.
The implementation
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 });
});
}Some details in this code matter:
onAbortreadstimerIdbefore the line that declares it. That works because the closure looks uptimerIdonly whenonAbortruns, and the listener is added after the timer is created. An abort event can't fire beforetimerIdhas a value.- The rejection value is
signal.reason, notnew Error('aborted'). This keeps the original reason, whether that is the defaultAbortError, aTimeoutError, or a custom value, and matches howfetchbehaves. - Optional chaining (
signal?.) makes the signal optional, sodelay(100)works with no options.
Using it
const controller = new AbortController();
delay(5000, { signal: controller.signal })
.then(() => console.log('finished'))
.catch((err) => {
if (err.name === 'AbortError') {
console.log('cancelled by the caller');
} else {
throw err;
}
});
setTimeout(() => controller.abort(), 1000);After one second this prints cancelled by the caller, and the 5-second timer is gone.
Common mistakes
| Mistake | Effect |
|---|---|
| Rejecting without clearing the timer | The promise rejects, but the timer still runs and keeps its callback in memory |
| Rejecting with a new generic `Error` | The caller loses the reason and can't tell a timeout from a user cancellation |
| Adding the listener before creating the timer | Usually harmless, but the code becomes harder to reason about |
| Not removing the listener on success | A long-lived signal collects stale listeners |
Exercise
Change delay() so it resolves with a value: delay(ms, value, { signal }) should resolve to value after ms milliseconds. Which lines change, and does the abort path need any change?
Show answer
Add a value parameter, delay(ms, value, { signal } = {}), and call resolve(value) inside the timer callback. The abort path stays the same: it still clears the timer and rejects with signal.reason, because the resolved value doesn't affect cancellation.
Exercise
If controller.abort() is called after the timer has already fired, what happens to the promise?
Show answer
Nothing. The promise has already resolved, and the timer callback removed the abort listener, so onAbort never runs. Even if it did run, the reject call would be ignored because a promise settles only once.