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

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

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

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

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

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

具体用法:

axios.CancelToken((cancel) => {
        cancel()
});

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

1. 构建一个Map数据结构

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

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

一、封装取消axios的类

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(部分)

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);

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用axios提供的取消请求的功能来取消上次请求并发送当前请求。首先,你需要创建一个取消令牌(cancel token),然后将其传递给你的请求。当你想要取消请求时,只需调用取消令牌的cancel方法。 以下是一个示例代码: ```javascript import axios from 'axios'; // 创建取消令牌 const cancelTokenSource = axios.CancelToken.source(); // 发送请求 axios.get('https://api.example.com/data', { cancelToken: cancelTokenSource.token }) .then(response => { // 处理响应数据 console.log(response.data); }) .catch(error => { if (axios.isCancel(error)) { // 请求取消 console.log('请求取消', error.message); } else { // 处理其他错误 console.log('请求发生错误', error.message); } }); // 取消上次请求并发送当前请求 cancelTokenSource.cancel('取消上次请求'); // 发送当前请求 axios.get('https://api.example.com/new-data', { cancelToken: cancelTokenSource.token }) .then(response => { // 处理响应数据 console.log(response.data); }) .catch(error => { if (axios.isCancel(error)) { // 请求取消 console.log('请求取消', error.message); } else { // 处理其他错误 console.log('请求发生错误', error.message); } }); ``` 在这个示例中,我们首先创建了一个取消令牌cancelTokenSource,并将其传递给第一个请求。然后,我们调用cancelTokenSource的cancel方法来取消上次请求,并发送当前请求。在请求的then和catch方法中,我们可以根据axios.isCancel方法来判断请求是否被取消,并进行相应的处理。 希望这个示例对你有帮助!如果你有任何其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值