Question presented to candidate: "A user navigates away from a page mid-request, or a request handler times out waiting on a slow downstream call. How do you actually stop that in-flight async work, rather than just ignoring its eventual result?"
What a strong answer should cover:
AbortControlleris a standard (originally browser, now also Node) API for cancelling an in-progress asynchronous operation: it exposes a.signal(anAbortSignal) that can be passed to any cancellation-aware API, and calling.abort()notifies every operation holding that signal.- 📌 Verified, not just described: a real
fetch()call to a deliberately unreachable address, given anAbortController's signal, was genuinely cancelled mid-flight — the call rejected with an actualAbortErrorat the moment.abort()was called, not merely at whatever time the request would have eventually timed out or failed on its own. fetch, many Node core APIs (fs.readFilewith a signal option, the HTTP client), and third-party libraries widely support accepting anAbortSignal— this is the standard, idiomatic cancellation mechanism in modern Node, not a one-off pattern specific to any single API.AbortSignal.timeout(ms)is a convenience constructor producing a signal that auto-aborts after a duration, without manually wiring asetTimeout+controller.abort()— 📌 verified directly, and distinguishable from a manual abort by its error name: a timeout-triggered abort rejects withTimeoutError, while a manually-called.abort()rejects withAbortError.- A single
AbortController's signal can be passed to multiple operations at once — calling.abort()once cancels all of them simultaneously, which is the real practical value for a scenario like "a client disconnected, stop every downstream call this request kicked off." - A precise answer names what
AbortControllerdoes not do: it does not forcibly kill a synchronous, already-running block of code (it cannot interrupt a tight synchronous loop mid-iteration) — it is a cooperative cancellation signal that async APIs must explicitly check/listen for, not a preemptive kill switch.
Clarifying questions expected:
- "Is the operation being cancelled genuinely async (fetch, a DB query) or a synchronous computation?" —
AbortControlleronly helps with the former. - "Does a single cancellation need to stop multiple concurrent operations at once?" — a real, common use for sharing one signal across several calls.
Code / implementation expected: Yes — a real fetch() genuinely cancelled mid-flight, with the actual AbortError/TimeoutError distinction, is the concrete, convincing demonstration.