Only know how to terminate XHR requests, perhaps for you is not enough!

TLDR:

When we need, we can terminate one or more requests by AbortController interface.

Foreword

So far, we have two common basic means to send a request and then partial refresh page content, one is XMR (XMLHttpRequest), and the second is fetch, we say one

XHR

For XHR, we probably already familiar with, 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 = () => {
  if (xhr.readyState === 4) {
    // do something
  }
}
xhr.send();

When we (such as repeat request) wants to terminate it for some reason, we just need to call abort.

xhr.abort();

Very convenient and very simple, but to fetch it?

fetch

First we look at the basic definition of fetch:

Here we see already know the answer, but we need to go look at the mentioned above AbortController.

AbortController

Initially es6 introduced fetch when, in fact, did not abort this function, but the majority of my friends also want the program to have this flexible api, so in 2015 it was mentioned this Issue , we try again after the injection promise of formula cancel or other hack and so on, we go through this agonizing eventually ushered AbortController and AbortSignal.

AbortController currently very simple, there is a system of property AbortController.signaland a request for interrupting.abort()

Light means nothing to say, we look at the code words:

// 启动一个node服务,其中包括一个api和一个html页面

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);

Here are the contents of the test.html

<!DOCTYPE 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, '请求成功');
        });
    </script>
</body>
</html>

After starting the service, we look at the content network.

We pay attention to two places, a representative of fetch request, a representative of the delay time of the request, that is, we define three seconds

Cancel fetch

This time we want to interrupt, you can do this:

<!DOCTYPE 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>
        // 增加了如下几行
        const controller = new AbortController();
        const signal = controller.signal;
        console.log(signal, 'signal的初始状态');
        signal.addEventListener('abort', function (e) {
            console.log(signal, 'signal的中断状态');
        });
        
        setTimeout(function() {
            controller.abort();
        }, 2000);
        // 增加部分结束

        fetch('/api', {signal})
        .then((res) => {
            console.log(res, '请求成功');
        });
    </script>
</body>
</html>

Run again, we get the following results:

We can clearly see from the figure, 2s after termination request, the request state becomes canceled, then aborted state transitions from false to true.

It is the way to cancel the operation to fetch us also, and it is actually quite suddenly. Hee hee.

compatibility

Although AbortController have been born a long time, but the current definition of mdn or 实验性技术view mdn we can find, in fact, most major browsers are supported, and if we develop a platform that can be used is still very new, I believe the near future It will certainly be used in large quantities. The front end of the road will be more smooth!

Finally, if the article can help bring a little help here, welcome attention, thumbs up, production is not easy, and the king of mutual encouragement to you!

Guess you like

Origin www.cnblogs.com/xiaoyuxy/p/12346344.html