Question presented to candidate: "A user navigates away from a search page before the results fetch() finishes. How would you cancel that in-flight request, and what exactly does the fetch's Promise reject with?"
What a strong answer should cover:
- 📌 Interview term:
AbortController— a real, built-in object exposing a single.abort(reason?)method and a.signalproperty (anAbortSignal) that can be passed tofetch()'s own{ signal }option to make that specific request cancellable. - 📌 Interview term: the real, direct answer to the prompt — verified directly: calling
controller.abort()with no argument genuinely produces a real, defaultDOMExceptionnamed"AbortError"assignal.reason, and the in-flightfetch()'s Promise genuinely rejects with exactly thatDOMException. - 📌 Interview term: the real custom-reason distinction — verified directly: calling
controller.abort("some custom reason")makessignal.reasongenuinely the EXACT custom value passed, and thefetch()Promise genuinely rejects with THAT value directly — not wrapped in aDOMException— a real, sharp, easy-to-miss distinction from the default no-argument case. - 📌 Interview term: pre-aborting — a precise answer names that a signal aborted BEFORE
fetch()is even called genuinely causes the fetch to reject immediately — verified directly — the network request never actually starts at all. - A precise answer names the real, practical cleanup pattern: calling
.abort()in auseEffectcleanup function (or equivalent lifecycle hook) when a component unmounts or a dependency changes, preventing a real, classic "setState after unmount" warning/bug from a request that finishes after it is no longer needed.
Clarifying questions expected:
- None — this is a definitional/practical question; directly demonstrating the real, verified rejection value in both the default and custom-reason cases is the strong signal.
Code / implementation expected: Yes — a real AbortController cancelling a real in-flight fetch(), verified with both a default abort and a custom-reason abort, plus the pre-abort case.