当页面跳转时,可以取消请求
或者当检索信息,更改过滤条件时,取消请求
取消请求,并不意味着服务器也会取消该请求的服务,但是客户端中断了该请求的响应
原理都是用了 xhr的abort方法
import axios from "axios"; let pending = []; let cancelToken = axios.CancelToken; function get(url) { return new Promise((resolve, injected) => { axios .get("/api", { cancelToken: new cancelToken(function executor(c) { pending.push({ url: config.url, c }); }), }) .then((res) => { resolve(res); finish(url); }) .catch((error) => { injected(error); finish(url); }); }); } function cancel(url) { for (let i = 0; i < pending.length; i++) { const item = pending[i]; if (item.url === url) { item.c(); pending.splice(i, 1); } } } function cancelAll() { for (let i = 0; i < pending.length; i++) { const item = pending[i]; item.c(); pending.splice(i, 1); } } function finish(url) { pending = pending.filter((item) => item.url != url); } export { get, cancel, cancelAll };