场景
一个按钮点击即可请求数据,但是会遇到的场景时,疯狂点击后,请求持续发送,若遇到某个接口加载比较缓慢,会有以前的来数据被拿到页面上来用,看到的便不是及时更新的数据;
axios 如何解决
axios提供传递一个 executor 函数到 CancelToken 的构造函数来创建 cancel token;从而打断之前的请求,保留最后一次新的
项目使用的VUE,于是
clickItem() {
const _this = this;
const CancelToken = axios.CancelToken;
this.cancelTokenFn && this.cancelTokenFn();
this.cancelTokenFn = null;
axios
.get("http://jsonplaceholder.typicode.com/comments", {
cancelToken: new CancelToken(function executor(c) {
// 这个参数 c 是CancelToken构造函数里面自带的取消请求的函数,这里把该函数当参数用
_this.cancelTokenFn = c;
})
})
.then(function(response) {
const data = response.data;
})
.catch(function(error) {});
},
其中会有一个C函数,C函数的内容查看了源码如下:
function cancel(message) {
if (token.reason) {
// Cancellation has