2Minutes: AbortController in JavaScript
What is AbortController ?
AbortController is a JavaScript class. We can instantiate an object from it and use methods such as controller.signal and controller.abort() to cancel asynchronous operations that support AbortSignal, such as fetch.
Let’s have a look at the following code:
const controller = new AbortController();
async function fetchData(stop = false) {
const res = await fetch("https://api.mouhammad.online/utimate-api", { signal: controller.signal });
if (stop === true) controller.abort();
}That’s the most basic usage of AbortController. It has many other useful use cases, such as implementing retry logic and cleaning up requests inside hooks, especially if you’re working with React. I highly recommend Googling these topics for a deeper understanding.
That’s 2Minutes, see you in the next one !
Sources
MDN: https://developer.mozilla.org/en-US/docs/Web/API/AbortController
Post on Medium: https://medium.com/@AlexanderObregon/canceling-fetch-requests-in-javascript-with-abortcontroller-98c11d2ab54e