If you have any questions or feedback, pleasefill out this form
Table of Contents
This post is translated by ChatGPT and originally written in Mandarin, so there may be some inaccuracies or mistakes.
In 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
AbortController
interface 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.
If you found this article helpful, please consider buying me a coffee ☕ It'll make my ordinary day shine ✨
☕Buy me a coffee