DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Gil Fink
Gil Fink

Posted on • Originally published at Medium on

Quick Tipβ€Šβ€”β€ŠWorking with AbortController

Quick Tipβ€Šβ€”β€ŠWorking with AbortController

There are some scenarios that you would like to cancel a server request. For example, your user is requesting a report which takes a lot of time to retrieve and changes her mind and request another report. What will you do? This is where AbortController can be very handy.

In this post I’ll shortly explain what is the AbortController and how to use it to abort fetch requests.

Stop Fetching Please

The AbortController is an object that can help you aborting fetch requests. How do you do that? First of all, create a new AbortController :

const abortCtrl = new AbortController();

Once you have an instance of AbortController you can use its API to abort fetch requests. The AbortController includes one property, signal, and one function, abort. The signal property is used to get an AbortSignal object. That object is used by fetch request for communication between the fetch request and the AbortController. You pass the AbortSignal object to fetch function as part of it’s options object. Here is a usage example:

const abortCtrl = new AbortController();
const signal = abortCtrl.signal;
fetch(url, { signal }).then((response) => {
  ...
}).catch((e) => {
  ... 
});

Once the fetch function includes a signal, you can abort the fetch request. If you need to abort the request all you have to do is to call the AbortController abort function. For example:

abortCtrl.abort();

Requests that are being aborted will result in fetch promise rejection with AbortError. That means that the catch callback function will run with with AbortError object which has an error code 20. Using that knowledge you can add logic to handle the abort scenario:

const abortCtrl = new AbortController();
const signal = abortCtrl.signal;
fetch(url, { signal }).then((response) => {
   ...
}).catch((e) => {
  if (error.code === 20) { // abort occurred
   // Do something after abort occurred
  }
});

Summary

This short post explained what is the AbortContoller and how to use it in your code. Let me know in the comments if you found it useful.

Top comments (0)

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!