· 2 min read

A New Way to Cancel Requests - AbortController

This article was auto-translated from Chinese. Some nuances may be lost in translation.

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 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 response Body, 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

Explore Other Topics