/  Technology   /  Fetch: Abort in Javascript
fetch

Fetch: Abort in Javascript

Fetch returns a promise and JavaScript generally has no concept of javascript “aborting” a promise. So how we can cancel an ongoing fetch?

Example:

If the user actions on our site indicate that the fetch is not needed any more.

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

 

Usage is very straightforward:

Create a controller:

let controller = new AbortController();

When abort():

⦁ controller.signal emits the javascript”abort” event
⦁ controller.signal.aborted property becomes true.

<!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>

 

Using with fetch:

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

⦁ AbortController is a simple javascript object that generates an abort event on its signal property when the javascript abort() method is called (and also sets signal.aborted to true).
⦁ 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 AbortController in our code. The “call abort()” → “listen to abort event” interaction is simple and universal. We can use it even without fetch.

 

Leave a comment