← Lessons

quiz vs the machine

Silver1050

Frontend

The Fetch API and Abort

Make HTTP requests and cancel them cleanly with AbortController.

4 min read · intro · beat Silver to climb

What fetch gives you

The fetch API is the modern, promise based way to make HTTP requests from the browser. It replaces the older XMLHttpRequest with a cleaner interface.

  • fetch(url) returns a promise that resolves to a Response object
  • The promise only rejects on network failure, not on HTTP error codes
  • You must check response ok or the status yourself for 404 or 500
  • Read the body with response json or response text, which are also promises

Why a 404 still resolves

A common trap is expecting fetch to throw on a 404. It does not. The request technically succeeded at the network layer, so you must inspect the status manually.

Cancelling with AbortController

Long running or stale requests waste bandwidth. An AbortController lets you cancel a fetch. Pass its signal to fetch, then call abort to stop it. The fetch promise rejects with an AbortError you can catch and ignore.

This is essential for type ahead search, where each keystroke should cancel the previous in flight request.

Request flow

Key idea

Fetch resolves on any HTTP response, so always check status yourself, and pair it with an AbortController to cancel stale requests.

Check yourself

Answer to earn rating on the learn ladder.

1. What happens when fetch receives an HTTP 404 response?

2. How do you cancel an in flight fetch request?