Skip to the solution
HardFrontend6 min read

Implement a Cancelable Promise (with CancelToken / AbortController)

624 views

The problem

Problem, as an interviewer would state it: "Implement a cancelable async operation using AbortController/AbortSignal — aborting it should genuinely stop the underlying work, not just have the caller ignore a late result."

Examples:

Code
const controller = new AbortController();
const p = cancelableDelay(5000, controller.signal);
controller.abort(); // p rejects almost immediately, the real underlying timer is cleared

Clarifying questions expected:

  • Does "cancel" mean genuinely stopping the underlying work (clearing a timer, aborting a real fetch), or just having the CALLER ignore a result that still arrives later?
  • What should happen if the signal is ALREADY aborted before the operation even starts?
  • Should the rejection use a specific, real, standard error type/name, for callers to distinguish an intentional cancellation from a genuine failure?

Code / implementation expected: Yes — real, direct proof that aborting mid-flight causes a genuinely FAST rejection, not one that waits for the original, full duration to elapse.

  • promise
  • cancelable
  • abort

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: aborting mid-flight causes a genuinely fast rejection (~20ms), not one that waits for the original full delay to elapse

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 149 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Implement deepEqual(a, b) handling NaN, -0, Dates, RegExp & circular refs

Continue