New way to cancel requests - AbortController
# FrontendIn the frontend, we primarily have two ways to send requests: XHR and Fetch. XHR has been around for, well… a long time. However, due to its complicated setup, it’s often wrapped into higher-level APIs for easier use, such as jQuery’s getJSON, axios, and RxJS’s AjaxObservable, among others.
In recent years, with the rising popularity of Promises, the Fetch API has significantly improved these issues. Besides returning a Promise for easy handling, the API is also quite straightforward.
However, despite these advantages, there is still a critical drawback. Fetch cannot cancel requests. While we can use a setTimeout approach to ignore the returned value, the request will still continue to wait. In XHR, we can use XMLHttpRequest.abort to cancel requests, but there is no similar API in Fetch.
Until recently! A new savior has finally appeared: AbortController.
The abort() method of the
AbortControllerinterface aborts a DOM request (e.g., a Fetch request) before it has completed. This can abort fetch requests, the consumption of any responseBody, and streams.
Using it is quite simple:
const abortController = new AbortController()
const signal = abortController.signal
Then just pass the signal into fetch.
fetch("/long-running", { signal: signal })
When you call abortController.abort, it will send the signal to the fetch. If the request has not completed when the signal is received, the request will be canceled.
fetch("/long-running", { signal: signal })
setTimeout(() => abortController.abort(), 5000)
If the request has not completed within five seconds, it will be canceled.
Wrapping it with RxJS might make the entire API even more convenient to use. However, the current browser support is still not very good.
Related Posts
- What to Pay Attention to When Using Images on the FrontendBased on an article by Jake Archibald, this post organizes how modern responsive images should be written: why `width`/`height` still matter, when to use CSS `aspect-ratio`, how to choose between AVIF and WebP, and how to use `picture`/`source`/`srcset` for switching images on mobile.
- CSS field-sizing — Auto-Resize Form Elements with One Line of CSSMaking a textarea auto-resize used to require JavaScript to watch scrollHeight. CSS field-sizing: content replaces all of that in one line, supporting textarea, input, and select.
- Make Your Hyperlink Underlines Look Better: text-underline-offsetBy default, underlines sit very close to the text, and some designers dislike this style. Personally, I don’t think it looks very good either.
- Why Web Design Shouldn’t Chase Pixel PerfectOnly pay attention to Pixel Perfect when it really matters; otherwise, it often leads to a lose-lose situation.