Advertisement
Intermediate JavaScript, Networking: Fetch, XHR, WebSockets & CORS

How do you cancel an in-flight fetch() request?

Short answer

Create an AbortController, pass its .signal to fetch()'s options, and call controller.abort() to cancel the request — fetch's Promise then rejects with an AbortError, which you can distinguish from real failures in your catch block.

Save JavaScript mock interview
Advertisement
AModel answer
Create an AbortController, pass its .signal to fetch()'s options, and call controller.abort() to cancel the request — fetch's Promise then rejects with an AbortError, which you can distinguish from real failures in your catch block.
const controller = new AbortController();
fetch('/api/data', { signal: controller.signal })
  .catch(err => { if (err.name === 'AbortError') console.log('cancelled'); });

controller.abort(); // cancels the request
Real-world example
Cancelling a previous search request when the user types a new character before the old one finishes.
Likely follow-ups
  • How would you implement a fetch timeout using AbortController?
Related topics