Stopping fetch requests

One action that we may want to do when making requests is to stop them. This could be for a multitude of reasons, such as:

Any of these reasons are great for stopping a request and now we have an API that can do this. The AbortController system allows us to stop these requests. What happens is that AbortController has a signal property. We attach this signal to the fetch request and when we call the abort method, it tells the fetch request that we do not want it to keep going with the request. It is very simple and intuitive. The following is an example:

(async function() {
const controller = new AbortController();
const signal = controller.signal;
document.querySelector('#stop').addEventListener('click', (ev) => {
controller.abort();
});
try {
const res = await fetch('http://localhost:8081/longload',
{signal});
const final = await res.text();
document.querySelector('#content').innerHTML = final;
} catch(e) {
console.error('failed to download', e);
}
})();

As we can see, we have set up an AbortController system and grabbed its signal property. We then set up a button that, when clicked, will run the abort method. Next, we see the typical fetch request, but inside the options, we pass the signal. Now, when we click the button, we will see that the request stops with a DOM error. We also see a bit of error handling in terms of async/await. aysnc/await can utilize basic try-catch statements to get to an error, just another way that the async/await API makes the code more readable than both the callback and the promise-based versions.

This is another API that is experimental and will most likely have changes in the future. But, we did have this same type of idea in XMLHttpRequest and it makes sense that the Fetch API will be getting it also. Just note that the MDN website is the best place to get up-to-date information on what browsers support and more documentation on any of the experimental APIs that we have discussed and will discuss in future chapters.

The fetch and promise system is a great way to get data from the server and to showcase the new way of handling asynchronous traffic. While we used to have to utilize callbacks and some nasty-looking objects, we now have a nice streamlined API that is quite easy to use. Even though parts of the API are in flux, just note that these systems are most likely going to be in place one way or another.