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 AbortErrorRules
- 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 rejectspwithreason— by default anErrorwhosenameis"AbortError".- Once
phas 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,
thenandcatchchain, andp instanceof Promiseholds.
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.