TLDR:

The AbortController interface terminates one or more requests as needed.

preface

So far, we’ve used two basic methods to send a request to partially refresh the content of the page, one is XMR(XMLHttpRequest), and the other is FETCH, let’s say one at a time

XHR

With XHR, we’re probably already familiar with the idea that when we want to send a request, we can do this:

const xhr = new XMLHttpRequest();
const method = 'GET';
const url = 'https://xxx';

xhr.open(method, url, true);
xhr.onreadystatechange = (a)= > {
  if (xhr.readyState === 4) {
    // do something
  }
}
xhr.send();
Copy the code

When we want to terminate it for some reason (such as a repeated request), we just call ABORT.

xhr.abort();

That’s convenient and neat, but what about fetch?

fetch

First let’s look at the basic definition of fetch:

  • Accept one required argument and one optional argument

    1. Define the resource, address, or Request object to retrieve
    2. Optional configuration objects, such as request mode, Body, Credentials, and so on, where we need to knowsignal, his definition is as follows:An AbortSignal object instance that allows you to communicate with or terminate the FETCH request via AbortController
  • The return value is a promise

At this point we already know the answer, but we need to take a look at the AbortController mentioned above.

AbortController

When FETCH was introduced in ES6, there was no abort function, but many applications wanted a flexible API, so it was mentioned in 2015. After that, people tried to inject Promise cancellations and other hacks. Finally we have AbortController and AbortSignal.

AbortController is very simple at the moment. It has an attribute called abortController.signal and an abort() that breaks requests.

It doesn’t mean anything. Let’s look at the code and say:

// Start a node service that includes an API and an HTML page const Koa = require(' Koa '); const fs = require('fs'); const app = new Koa(); const sleep = () => { return new Promise(res => { setTimeout(function() { res(); }, 3000); }); }; app.use(async ctx => { if (ctx.request.url === '/api') { await sleep(); ctx.body = 'Hello World'; } else { ctx.status = 200; ctx.respond = false; fs.createReadStream('./test.html').pipe(ctx.res); }}); app.listen(3000);Copy the code

Here is the content of test.html


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <script>
        fetch('/api')
        .then((res) = > {
            console.log(res, 'Request successful');
        });
    </script>
</body>
</html>
Copy the code

After starting the service, let’s take a look at the contents of Network.

Let’s note two places, one for the FETCH request, and one for the delay time of the request, which we defined as three seconds

Cancel the fetch

When we want to interrupt, we can do this:


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // Add the following lines
        const controller = new AbortController();
        const signal = controller.signal;
        console.log(signal, 'Initial state of signal');
        signal.addEventListener('abort'.function (e) {
            console.log(signal, 'Signal interrupt status');
        });
        
        setTimeout(function() {
            controller.abort();
        }, 2000);
        // The addition is finished

        fetch('/api', {signal})
        .then((res) = > {
            console.log(res, 'Request successful');
        });
    </script>
</body>
</html>
Copy the code

Running it again, we get the following:

As can be seen from the diagram, the request was terminated after 2 seconds, the request status changed to canceled, and the aborted state changed from False to True.

That’s it. We canceled the fetch, too. Hee hee.

compatibility

AbortController has been around for a long time, but the MDN definition is still experimental. Looking at MDN, we can see that most of the major browsers support it. If we develop a platform that is new, we can still use it. The front end of the road will be more and more smooth!

Finally, if this article can help to bring you a little help, welcome attention, like, production is not easy, and you encourage!