DEV Community

Cover image for Smarter Code With AbortController!
Parsa Frahani
Parsa Frahani

Posted on

Smarter Code With AbortController!

For example, think that you fetched an API but for any reason, you want to cancel it. what will you do? or maybe you have an event on some button and you want that event don't work if something happens. what will do here? call another event?
All of these ideas that you have may work, but they are not smart!

Image description

With the help of ES6 now you can cancel your request or event at any time with better & also with smarter code. so without wasting any time let's get into it.

What is AbortController?

So basically as I said, AbortController is used for canceling events or requests easily. We have two parts to work with it, one is the usual AbortController and the other one is AbortSignal. With the use of AbortSignal we can have access to the API's signal and call our AbortController, then set some conditions that if X happens cancel fetching data. but to understand better and deeper let's see it in the code.

Using AbortController In JavaScript:

Take a quick look at the code below.

const controller = new AbortController();

const functionFetch = async () => {
  try {
    const url = await fetch("https://catfact.ninja/fact", {
      signal: controller.signal,
    });
    const todo = await url.json();
    console.log(todo);
  } catch (error) {
    if (error.name === "AbortError") {
      console.log("this is an abort error ==>", error);
    }
  }
};
functionFetch();
controller.abort();
Enter fullscreen mode Exit fullscreen mode

It's okay not to get it all, but let me break it down.

So first to start it we need to make a new AbortController as we did so. Then I fetched an API and got access to its signal like an object and gave it the property of controller.signal, but what does this signal do?

So basically we use this property to communicate with the outer abort (as we are setting it for our API).

After that, I made a Constance value and named it todo that simply holds the JSON version of our data. In the catch part, I checked if the error name is AbortError which means our API got canceled because of our abort I'll log and string with a text.

In the end, I called the function to make it work and also called the controller.abort to cancel the API. So if we wanted to cancel the API call we simply call the controller.abort anywhere we wanted. If you check the console we should have this text there:

Image description

And by the way, you can name the controller anything that you want as it's obvious or you can specify some conditions like if/else statements. and that's how you use AbortController in your Project. easy huh?

How To Use It In The Events?

Most programmers think that AbortController is just for API and they don't know they can use it to stop events too. before I explain how you should use it to stop events take a quick look at the code below.

const controller = new AbortController();
const { signal } = controller;

const log = function () {
  console.log("mouse moved");
};

const remove = function () {
  console.log("Event stoped");
  controller.abort();
};

window.addEventListener("mousemove", log, { signal });
window.addEventListener("mouseup", remove, { signal });


Enter fullscreen mode Exit fullscreen mode

Understanding the code above got to be easy but I'll explain it as well.

So this is the code that we had before but now we are canceling the log event by clicking. But notice something in the events, I gave them a third property and that signal. By doing that I', telling them that on this event call our AbortController.

If you move the mouse it will log the string in the log function and if you click the AbortController will stop the log function and it's not going to work anymore (before stopping the log function we will see Event stopped as you can see).

Image description

If you click multiple times it will stop the event several times as you know (so the AbortController will be called several times).

But did you know that we have an event named abort?

Abort Event In JS:

Honestly, That was so interesting for me. so we have an event named abort that whenever we call AbrotController this event will call too. look here to understand better:

const controller = new AbortController();
const { signal } = controller;


const log = function () {
    console.log("mouse moved");
  };

  const remove = function () {
    console.log("Event stoped");
    controller.abort();
  };

  window.addEventListener("mousemove", log, { signal });
  window.addEventListener("mouseup", remove, { signal });

  // I ADDED THIS👇
  signal.addEventListener("abort", () => {
    console.log("this is abort event");
  });

Enter fullscreen mode Exit fullscreen mode

This is the last part code but with a new event as you can see. So simply we call our event on the signal and we tell it whenever something aborted log this string. The output should be like this:

Image description

Conclusion

Now that you are at the end of this blog keep in mind that AbortControllers can be more complicated when you use libraries like Axios. I hope this blog helped you understand the basics of abort controllers and how to use them in real projects.

If you have any opinion feel free to share it in the comments🙏.
Thanks for your support.

Top comments (0)