A New Way to Cancel Requests - AbortController
In front-end development, there are mainly two ways to send requests: XHR and Fetch. XHR is an API that has been around since, well… a very long time ago. However, because configuring it is quite cumbersome, it was often wrapped into higher-level APIs like jQuery’s getJSON, axios, RxJS’s AjaxObservable, and so on.
In recent years, the Fetch API, which grew popular alongside Promises, has significantly improved upon these issues. In addition to returning a Promise for easier handling, the API itself is remarkably simple.
Despite this, there was still one fatal flaw: Fetch could not cancel requests. Although we could use setTimeout to ignore the returned value, the request itself would still keep waiting. In XHR, we could use XMLHttpRequest.abort to cancel, but Fetch lacked a similar API.
Until recently! A new savior has finally arrived: AbortController.
The abort() method of the
AbortControllerinterface aborts a DOM request (e.g. a Fetch request) before it has completed. This is able to abort fetch requests, consumption of any responseBody, and streams.
It is very simple to use:
const abortController = new AbortController()
const signal = abortController.signal
Then, simply pass signal into fetch:
fetch("/long-running", { signal: signal })
When you call abortController.abort, the signal is communicated to fetch. If the request hasn’t completed by the time it receives the signal, the request will be canceled.
fetch("/long-running", { signal: signal })
setTimeout(() => abortController.abort(), 5000)
If the request is not completed within five seconds, it will be canceled.
Wrapping it with RxJS might make the API even more convenient to use. However, current browser support is still not great.
Related Posts
- Recreating My Room with Three.js Using React Three Fiber, I brought my real room into the browser—turning physical objects into an interactive table of contents, and using spatial memory to tell the story of my life and work over the past few years.
- Things to Keep in Mind When Using Images in Frontend Development Expanding on Jake Archibald's article, this post organizes how modern responsive images should be written: why width/height are still necessary, when to use CSS aspect-ratio, how to choose between AVIF and WebP, and using picture/source/srcset for art direction on mobile devices.
- CSS field-sizing — Auto-resize Form Elements with a Single Line of CSS Previously, auto-resizing a textarea required listening to scrollHeight in JavaScript. With CSS field-sizing: content, a single line replaces it all, supporting textarea, input, and select. This article covers the pain points of older approaches and how to use field-sizing.
- Make Your Link Underlines Look Better: text-underline-offset By default, underlines sit very close to the text. Some designers dislike this look, and personally, I don't think it looks great either.