Cancellable Promise
MediumPromises & Async15 min5 tests
Implement createCancellable(promise) that wraps a promise and adds cancellation support.
Requirements
- Return an object
{ promise, cancel() }. - The returned
promiseresolves/rejects with the original promise's value, unless cancelled. - When
cancel()is called, the returned promise rejects with"Cancelled". - The original promise still runs; its result is simply ignored after cancellation.
Example
const { promise, cancel } = createCancellable(
new Promise(r => setTimeout(() => r('done'), 100))
);
cancel();
await promise; // rejects with "Cancelled"Hints (5)
- Wrap the original promise in a new Promise constructor.
- Store a reference to the reject function from the wrapper.
- Use a boolean flag to track whether cancel has been called.
- In the .then/.catch of the original, check the flag before resolving or rejecting.
- cancel() sets the flag and calls reject with "Cancelled".
Topics
- Promises & Async
Asked at
Netflix · Uber · Airbnb
