← Lessons

quiz vs the machine

Gold1460

Frontend

The Fetch API and AbortController

Fetch returns a promise, and an AbortController signal lets you cancel a request in flight.

5 min read · core · beat Gold to climb

Fetch basics

The fetch function returns a promise that resolves to a Response. A key gotcha is that fetch only rejects on network failure, not on HTTP error status.

  • A 404 or 500 still resolves successfully.
  • You must check response ok or the status yourself and throw if needed.
  • Call response json or response text to read the body, which returns another promise.

Cancelling with AbortController

An in flight request can be cancelled with an AbortController. You create a controller, pass its signal to fetch, and call abort to cancel.

  • Aborting rejects the fetch promise with an abort error you can catch and ignore.
  • This matters for search as you type, where each keystroke should cancel the previous request.
  • It also prevents setting state after a component unmounts.

A common pattern is to store the controller, abort it before starting a new request, and create a fresh one each time.

Key idea

Fetch resolves even on 404 so check response ok, and pass an AbortController signal to cancel stale requests like rapid search queries.

Check yourself

Answer to earn rating on the learn ladder.

1. Does fetch reject the promise on a 404 response?

2. What is the main use of AbortController with fetch?

3. What happens when you call abort on the controller?