#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.

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

Source

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

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 · ES6Pratik Rai ·

JavaScript

Promise Time Limit

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

JavaScript · ES6Pratik Rai ·

JavaScript

Promisify a Callback Function

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

JavaScript · ES6Pratik Rai ·