In the frontend, we mainly have two ways to send requests: XHR
and Fetch
. XHR is an API that has been around for a long time. However, due to its complicated configuration, it is often wrapped into higher-level APIs like jQuery
's getJSON
, axios
, RxJS's AjaxObservable
, etc.
In recent years, with the increasing popularity of Promises, the Fetch API has greatly improved these issues. Apart from returning a Promise for easy handling, the API itself is also quite simple.
However, despite these advantages, there is still one fatal drawback. Fetch cannot cancel requests. Although we can ignore the returned value using setTimeout
, the request still continues to wait. In XHR, we can use XMLHttpRequest.abort
to cancel the request, but there is no similar API in fetch.
Until recently! A new savior has finally emerged: AbortController
.
The abort() method of the
AbortController
interface 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's very simple to use.
const abortController = new AbortController()
const signal = abortController.signal
Then pass signal
into fetch.
fetch("/long-running", { signal: signal })
When you call abortController.abort
, it will be passed to fetch through the signal. If the request hasn't completed when the signal is received, the request will be canceled.
fetch("/long-running", { signal: signal })
setTimeout(() => abortController.abort(), 5000)
If the request hasn't completed within five seconds, it will be canceled.
Pairing it with RxJS can make the entire API more convenient to use. However, the current browser support is not very good.