zoukankan      html  css  js  c++  java
  • axios 设置全局取消请求

    当页面跳转时,可以取消请求
    或者当检索信息,更改过滤条件时,取消请求
    取消请求,并不意味着服务器也会取消该请求的服务,但是客户端中断了该请求的响应
    原理都是用了 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 };
  • 相关阅读:
    Search in Rotated Sorted Array
    Search insert position
    二分法感悟
    The Smallest Difference
    Lintcode: Nuts & Bolts Problem
    167. Two Sum II
    登录页面
    注册页面
    在线版简易计算器
    简单工厂模式
  • 原文地址:https://www.cnblogs.com/hill-foryou/p/15382818.html
Copyright © 2011-2022 走看看