call(back)
FrontendmediumSign in to star problems

Abortable Promise

Native promises can't be cancelled. Build AbortablePromise, a Promise subclass whose work can be stopped from outside.

const p = new AbortablePromise((resolve, reject, onAbort) => {
  const id = setTimeout(() => resolve("done"), 1000);
  onAbort(() => clearTimeout(id));   // how to stop the work
});
p.abort();                           // runs the cleanup, rejects p with an AbortError

Rules

  • The executor receives a third argument, onAbort(cleanup), which registers the function that stops the work.
  • p.abort(reason?) on a pending promise runs the cleanup, if one was registered, and rejects p with reason — by default an Error whose name is "AbortError".
  • Once p has settled — resolved, rejected, or already aborted — abort() does nothing: no cleanup, no change of outcome.
  • Everything else behaves like a native promise: a throwing executor rejects, then and catch chain, and p instanceof Promise holds.

The grader stubs setTimeout and clearTimeout with a virtual clock and records what your callbacks see, in order.

Hints

Hint 1

Native promises don't expose their state, so track it yourself: wrap the resolve and reject you pass to the executor so they set a settled flag, and have abort() return early when it is set.

Hint 2

Capture the real reject and the registered cleanup in closures inside the function you hand to super(); after super() returns, store an abort function on the instance. this isn't available before super().

Hint 3

Wrap the executor call in try/catch and reject through the same guarded path, so a throwing executor also marks the promise settled.

Asked at