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 promise resolves/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)
  1. Wrap the original promise in a new Promise constructor.
  2. Store a reference to the reject function from the wrapper.
  3. Use a boolean flag to track whether cancel has been called.
  4. In the .then/.catch of the original, check the flag before resolving or rejecting.
  5. cancel() sets the flag and calls reject with "Cancelled".

Topics

  • Promises & Async

Asked at

Netflix · Uber · Airbnb

Join Us
blur