As we know, fetch returns a promise. And JavaScript generally has no concept of “aborting” a promise. So how can we cancel an ongoing fetch? E.g. if the user actions on our site indicate that the fetch isn’t needed any more.
There’s a special built-in object for such purposes: AbortController. It can be used to abort not only fetch, but other asynchronous tasks as well.
The usage is very straightforward:
The AbortController object
Create a controller:
let controller = new AbortController();
A controller is an extremely simple object.
- It has a single method
abort(), - And a single property
signalthat allows to set event listeners on it.
When abort() is called:
controller.signalemits the"abort"event.controller.signal.abortedproperty becomestrue.
Generally, we have two parties in the process:
- The one that performs a cancelable operation, it sets a listener on
controller.signal. - The one that cancels: it calls
controller.abort()when needed.
Here’s the full example (without fetch yet):