#Promises#Async

Cancellable Promise

Give the caller a way to stop waiting on a promise — the pattern behind cancelling a request when a component unmounts.

By Pratik RaiMedium

Write cancellable(promise) returning { promise, cancel }.

The returned promise settles exactly as the original does, except that calling cancel() before it settles rejects it with the string "Cancelled". Calling cancel() afterwards must do nothing.

Examples

Input:

JSfile.javascript
1const { promise, cancel } = cancellable( 2 new Promise((r) => setTimeout(() => r('done'), 500)) 3); 4cancel(); 5promise.catch(console.log);

Output:

"Cancelled"

cancel() ran before the 500ms timer, so the result never arrives.

Constraints

  • cancel may be called any number of times

Notes

  • This stops you waiting; it does not stop the work. AbortController is what actually aborts a fetch.

How to solve it

A promise you can walk away from

A promise has no cancel. Once created it will settle, and the only question is whether anyone is still listening. Cancellation is therefore about the listener, not the work.

Approach

Make a second promise whose reject you keep, and race it against the original.

Implementation

JSfile.javascript
1function cancellable(promise) { 2 let cancel; 3 const gate = new Promise((_, reject) => { cancel = () => reject('Cancelled'); }); 4 gate.catch(() => {}); 5 return { promise: Promise.race([promise, gate]), cancel }; 6}

Worth knowing

You need no "has it settled" flag: a promise settles once, so a cancel() after the fact is a no-op for free.

Be honest about what this does. The underlying work carries on — the timer still fires, the request still completes and its response is still downloaded. AbortController passed to fetch genuinely aborts the request, and is what you would use in a component that unmounts mid-flight.

Goal: Reject with "Cancelled" when cancel comes first, and behave like the original otherwise.

Frequently asked questions

Can you cancel a promise in JavaScript?
Not directly — a promise has no cancel method and will settle once created. What you can cancel is your interest in it, by racing it against a promise you are able to reject yourself.
What is the difference between this and AbortController?
This stops you waiting; the underlying work continues. AbortController passed to fetch genuinely aborts the request, so the browser stops downloading and the server sees a dropped connection.
Why does cancelling after the promise settled do nothing?
Because a promise settles exactly once. If the original won the race, rejecting the loser afterwards has no observable effect, so you need no extra flag to guard against it.
Where does this matter in React?
A component that unmounts while a request is in flight. Without cancellation the response arrives, sets state on an unmounted component, and in the worst case overwrites newer data from a request that started later.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Promise Pool With a Concurrency Limit

Run a list of async tasks with a hard limit on how many are in flight at once — the concurrency control Promise.all does not give you.

JavaScript · ES6 — Pratik Rai ·

JavaScript

Time Out an Async Function

Wrap an async function so it gives up after a deadline — the building block behind every request timeout.

JavaScript · ES6 — Pratik Rai ·

JavaScript

Promisify a Callback Function

Convert a Node-style (error, value) callback API into one that returns a promise.

JavaScript · ES6 — Pratik Rai ·