Here are two common patterns for making your async work cancellable in JavaScript:
1. Using AbortController / AbortSignal
The AbortController API is now widely supported (in browsers and Node.js). You pass its signal into anything that honors it (e.g. fetch, ReadableStream, some libraries). When you call controller.abort(), the signal fires an “aborted” event and the underlying operation rejects with an AbortError.
// 1) Your cancellable function accepts an AbortSignal
async function fetchWithCancel(url, signal) {
// fetch honors the signal natively
const response = await fetch(url, { signal });
if (!response.ok) throw new Error('HTTP error');
return response.json();
}
// 2) A helper that bundles promise + cancel
function makeCancellableFetch(url) {
const controller = new AbortController();
const promise = fetchWithCancel(url, controller.signal);
return {
promise,
cancel: () => controller.abort(),
};
}
// Usage
const { promise, cancel } = makeCancellableFetch('/api/data');
promise
.then(data => console.log('got data', data))
.catch(err => {
if (err.name === 'AbortError') {
console.log('Fetch was cancelled');
} else {
console.error('Fetch failed:', err);
}
});
// later…
cancel(); // triggers AbortError inside fetchWithCancel
Pros
- Native support in modern environments
- Underlying I/O (fetch, streams) actually stops
- Standardized error (
AbortError)
2. Rolling Your Own “Cancelable Promise”
If you have some custom async work (e.g. timers, loops, 3rd-party callbacks) you can wrap it in a “cancelable promise” pattern:
function makeCancelable(promiseExecutor) {
let isCanceled = false;
const wrappedPromise = new Promise((resolve, reject) => {
promiseExecutor(
value => {
if (!isCanceled) resolve(value);
else reject({ isCanceled: true });
},
error => {
if (!isCanceled) reject(error);
else reject({ isCanceled: true });
}
);
});
return {
promise: wrappedPromise,
cancel() { isCanceled = true; }
};
}
// Example: a cancellable timer
function cancellableDelay(ms) {
return makeCancelable((resolve, reject) => {
const id = setTimeout(() => resolve(`Waited ${ms}ms`), ms);
// if canceled before timeout, clear it
promiseExecutor.cancel = () => {
clearTimeout(id);
reject(`canceled after ${ms}ms`);
};
});
}
// Usage
const { promise, cancel } = cancellableDelay(5000);
promise
.then(console.log)
.catch(err => {
if (err.isCanceled) console.log('Operation canceled!');
else console.error(err);
});
// …cancel before 5s
cancel();
Pros / Cons
- ✅ Fine for simple self-contained tasks (timers, loops)
- ❌ Doesn’t magically stop underlying work unless you do it yourself
- ⚠️ You must manually clean up (e.g.
clearTimeout, remove event listeners)
Which to Choose?
- I/O or browser APIs (fetch, streams, geolocation, WebSockets…): use
AbortController.
- Custom tasks (timers, XHR wrappers, 3rd-party libs): roll your own, ensuring you clean up any resources when canceled.
Any follow-up on a specific library or use-case you’re targeting? 😊