Cancellable Promise

PromisesAsyncCancellation

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

Example 1
Input
const { promise, cancel } = cancellable(
  new Promise((r) => setTimeout(() => r('done'), 500))
);
cancel();
promise.catch(console.log);
Output
"Cancelled"
Explanation
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.

Hints

Read the full write-up for Cancellable Promise
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it