0
点赞
收藏
分享

微信扫一扫

模拟实现axios取消请求功能

棒锤_45f2 2022-02-28 阅读 82
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.26.0/axios.min.js"></script>
    <title>模拟实现axios取消请求功能</title>
</head>

<body>
    <button>发送请求</button>
    <button>取消发送</button>
    <script>
        function Axios(config) {
            this.config = config;
        }
        Axios.prototype.request = function (config) {
            return configRequest(config);
        };

        function configRequest(config) {
            return xhrAdapter(config);
        };

        function xhrAdapter(config) {
            return new Promise((resolve, reject) => {
                let xhr = new XMLHttpRequest();
                xhr.open(config.method, config.url);
                xhr.send();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200 && xhr.status < 300) {
                            resolve({
                                status: xhr.status,
                                statusText: xhr.statusText
                            })
                        }
                        //  else {
                        //     reject(new Error('请求出错了'))
                        // }
                    }
                }
                if (config.cancelToken) {
                    config.cancelToken.promise.then(value => {
                        xhr.abort();
                        reject('请求已经取消')
                    })
                }
            })
        }

        function CancelToken(executor) {
            let resolvePromise;
            this.promise = new Promise(resolve => {
                resolvePromise = resolve;
            });
            executor(function cancel() {
                resolvePromise();
            })
        }
        const context = new Axios({});
        const axios = Axios.prototype.request.bind(context);

        let btns = document.querySelectorAll('button');
        let cancel = null;
        btns[0].onclick = function () {
            if (cancel) {
                cancel();
            }
            axios({
                method: 'GET',
                url: ' http://localhost:3000/posts',
                cancelToken: new CancelToken(c => {
                    cancel = c;
                })
            }).then(response => {
                console.log(response);
                cancel = null;
            }, error => {
                console.log(error)
            })
        }
        btns[1].onclick = function () {
            cancel();
        }
    </script>
</body>

</html>
举报

相关推荐

0 条评论