猫码让前端飞vue

Axios 取消重复请求

2020-11-06  本文已影响0人  ComfyUI

有什么用?

基本使用

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  }),
});

// cancel the request
cancel();

具体使用

// https://github.com/Ewall1106/mall/blob/master/src/utils/request.js
import axios from 'axios';

const CancelToken = axios.CancelToken;
const pendingReq = {};

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      // 取消请求
      const key = config.url + '&' + config.method;
      pendingReq[key] && pendingReq[key]('操作太频繁了~');
      config.cancelToken = new CancelToken((c) => {
        pendingReq[key] = c;
      });
      // ...
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 取消请求
    const key = response.config.url + '&' + response.config.method;
    pendingReq[key] && delete pendingReq[key];

    // ...
  },
  (error) => {
    console.log('err' + error);
    Toast.fail(error.message);
    return Promise.reject(error);
  }
);

export default service;
上一篇 下一篇

猜你喜欢

热点阅读