/  Technology   /  How to abort a batch of async fetch requests in Javascript?
Async in js

How to abort a batch of async fetch requests in Javascript?

 

As we know, fetch returns a promise. And JavaScript async generally has no concept of “aborting” a promise. So how can we cancel an ongoing javascript fetch?

 

Example:

If the user actions on our site indicate that the fetch isn’t needed any more.

There’s a special built-in object javascript for such purposes: AbortController. It can be used to async abort not only fetch, but other asynchronous tasks as well.

<!DOCTYPE html>
<script>
"use strict";
let controller = new AbortController();
let signal = controller.signal;
// The party that performs a cancelable operation
// gets the "signal" object
// and sets the listener to trigger when controller.abort() is called
signal.addEventListener('abort', () => alert("abort!"));
// The other party, that cancels (at any point later):
controller.abort(); // abort!
// The event triggers and signal.aborted becomes true
alert(signal.aborted); // true
</script>

As we can see, javascript AbortController is just a mean to pass abort events when javascript abort() is called on it.

We could implement the same kind of javascript event listening in our code on our own, without the javascript AbortController object.

But what’s valuable is that fetch knows how to work with the javascript AbortController object. It’s integrated in it.

 

Using with fetch:

let controller = new AbortController();
fetch(url, {
signal: controller.signal
});

Javascript AbortController is a simple object that generates an javascript abort event on its signal property when the abort() method is called (and also sets signal.aborted to true).
Javascript fetch integrates with it: we pass the signal property as the option, and then fetch listens to it, so it’s possible to abort the fetch.
We can use javascript AbortController in our code. The javascript “call abort()” → “listen to abort event” interaction is simple and universal. We can use it even without fetch.

 

Leave a comment