模拟实现axios取消请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| <!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"> <title>Document</title> <style> </style> </head> <body> <div class="container"> <h2></h2> <button class = 'btn btn-primary'>发送请求</button> <button class = 'btn btn-warning'>取消请求</button> </div> <script> function Axios(config){ this.config = config } Axios.prototype.request = function (config){ return dispatchRequest(config) } function dispatchRequest(config){ return xhrAdapter(config) } function xhrAdapter(config){ return new Promise ((resolve, reject) => { const 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(new Error('请求已被取消')) }) } }) } const context = new Axios({}) let axios = Axios.prototype.request.bind(context) function CancelToken(executor){ var resolvePromise; this.promise = new Promise((resolve) => { resolvePromise = resolve }) executor(function (){ resolvePromise() }) }
const btns = document.querySelectorAll('button') let cancel = null ; btns[0].onclick = function () { if(cancel !== null){ cancel() }
let cancelToken = new CancelToken(function (c){ cancel = c }) axios({ method: "GET", url: 'http://localhost:3000/posts', cancelToken: cancelToken }).then(response => { console.log(response) cancel = null; }) } btns[1].onclick = function (){ cancel() }
</script> </body> </html>
|
为了我们很高的观察, 我们在启动服务的时候加一个延时:
结果