axios进阶——取消已经发出去的请求

首先,引入取消已经发出去的请求的必要性:

  1. 防止重复请求:当用户快速连续触发同一操作(比如多次点击按钮发送同一个请求),这个函数可以确保只有最后一个请求被执行,之前的相同请求会被取消,从而避免了因重复请求导致的数据不一致或服务器压力。

  2. 优化性能和体验 :通过维护一个待处理请求的映射表(pendingMap),可以有效管理网络请求队列,特别是在用户交互频繁的应用中,有助于提升应用响应速度和用户体验。

  3. 资源管理:及时取消不再需要的HTTP请求可以释放浏览器或应用的资源,尤其是在移动端或网络环境不稳定的情况下,有助于节省数据流量和电池使用。

解决方案:CancelToken是axios库提供的一种机制,允许你取消已发出但尚未完成的HTTP请求。

具体用法:

javascript 复制代码
axios.CancelToken((cancel) => {
        cancel()
});

封装进入axios中,大体思路为:

  1. 构建一个Map数据结构

2.每发送一个网络请求,就将该请求映射入Map结构中

3.存入前进行检查,如果存在该映射关系,将旧的请求cancel()取消掉,将新的映射存入

一、封装取消axios的类

TypeScript 复制代码
let pendingMap = new Map<string, Canceler>();

export const getPendingUrl = (config: AxiosRequestConfig) => [config.method, config.url].join('&');

export class AxiosCanceler {
  /**
   * Add request
   * @param {Object} config
   */
  addPending(config: AxiosRequestConfig) {
    // 取消相同的请求
    this.removePending(config);
    // 构造key
    const url = getPendingUrl(config);
    config.cancelToken =
      config.cancelToken ||
      new axios.CancelToken((cancel) => {
        if (!pendingMap.has(url)) {
          // If there is no current request in pending, add it
          pendingMap.set(url, cancel);
        }
      });
  }

  /**
   * @description: Clear all pending
   */
  removeAllPending() {
    pendingMap.forEach((cancel) => {
      cancel && isFunction(cancel) && cancel();
    });
    pendingMap.clear();
  }

  /**
   * Removal request
   * @param {Object} config
   */
  removePending(config: AxiosRequestConfig) {
    const url = getPendingUrl(config);

    if (pendingMap.has(url)) {
      // If there is a current request identifier in pending,
      // the current request needs to be cancelled and removed
      const cancel = pendingMap.get(url);
      cancel && cancel(url);
      pendingMap.delete(url);
    }
  }

  /**
   * @description: reset
   */
  reset(): void {
    pendingMap = new Map<string, Canceler>();
  }
}

二、封装axios(部分)

TypeScript 复制代码
import { AxiosCanceler } from './axiosCancel';


this.axiosInstance = axios.create(options);
const axiosCanceler = new AxiosCanceler();

this.axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
      axiosCanceler.addPending(config);
     
      return config;
}, undefined);
相关推荐
cos3 分钟前
React RCE 漏洞影响自建 Umami 服务 —— 记 CVE-2025-55182
前端·安全·react.js
ConardLi10 分钟前
分析了 100 万亿 Token 后,得出的几个关于 AI 的真相
前端·人工智能·后端
阿珊和她的猫18 分钟前
UTF - 8 编码在 HTML 中的重要性
前端·html
加油乐35 分钟前
css及js实现正反面翻转
前端·javascript·css
恶猫41 分钟前
抖音直播时,飘窗提示的html窗口,主播不在,正在喝9
前端·html·直播·抖音·素材
霁月的小屋1 小时前
Vue组件通信全攻略:从基础语法到实战选型
前端·javascript·vue.js
腾讯云云开发1 小时前
【你可能不知道的开发技巧】一行代码完成小程序的CloudBase鉴权登录
前端·后端·微信小程序
Micro麦可乐1 小时前
前端真的能防录屏?EME(加密媒体扩展) DRM 反录屏原理 + 实战代码
前端·媒体·eme·drm·前端防盗录
一 乐1 小时前
校园社区系统|基于java+vue的校园悬赏任务平台系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
晚霞的不甘1 小时前
华为云 DevUI 实战开发指南:构建现代化前端应用的最佳实践
前端·华为云