Loading article...
A cancelable promise wrapper allows you to prevent promise handlers from executing after cancellation. This is useful for avoiding state updates in unmounted React components or canceling outdated API responses.
function makeCancelable(promise) { let hasCanceled = false; const wrapped = new Promise((resolve, reject) => { promise .then((val) => (hasCanceled ? reject({ canceled: true }) : resolve(val))) .catch((err) => (hasCanceled ? reject({ canceled: true }) : reject(err))); }); return { promise: wrapped, cancel() { hasCanceled = true; } }; }
const task = new Promise((res) => setTimeout(() => res("Done"), 1000)); const cancelable = makeCancelable(task); cancelable.promise .then(console.log) .catch((err) => { if (err.canceled) console.log("Canceled"); else console.error(err); }); setTimeout(() => cancelable.cancel(), 500); // cancel before it resolves
.cancel() is called before resolution, the promise rejects with { canceled: true }..then()/.catch() from running.AbortController for cancelable fetch requests or actual task termination.Test your understanding with 3 quick questions