Intermediate JavaScript Interview QuestionsIntermediatePractical
JavaScript · Question 51
How does AbortController help cancel asynchronous browser operations such as fetch?
Direct answer
AbortController exposes an AbortSignal that supported APIs can observe; calling controller.abort() marks the signal aborted and lets those APIs terminate or reject their work cooperatively.
A common pattern is const controller = new AbortController(); fetch(url,{signal:controller.signal}); and later controller.abort(). The API receiving the signal decides how to react to cancellation.
- Use cancellation when a component unmounts, a newer search supersedes an older request, or the user explicitly cancels an operation.
- An AbortSignal stays aborted; do not try to “reset” and reuse the same controller for a new independent operation.
- Multiple operations can share a signal when they should be cancelled as one group.
- Aborting a client request does not guarantee that a server-side mutation was never started or completed. Application-level idempotency and transaction semantics are separate concerns.
Cancellation also prevents stale responses from racing with newer UI state, but request identity checks can still be useful when multiple operations are allowed to finish.