jahnsli
V2EX  ›  Vue.js

取消重复的 axios 请求时如何避免失败?

  •  
  •   jahnsli · Nov 8, 2022 · 2851 views
    This topic created in 1294 days ago, the information mentioned may be changed or developed.

    我尝试在 Axios 中取消重复请求,但它可能仍会发送重复请求。

    import type { AxiosRequestConfig } from 'axios';
    
    export default class CancelRequest {
    
      pendingRequestList: Map<any, any>;
    
      constructor() {
        this.pendingRequestList = new Map();
      }
    
    
      addPendingRequest = (config: AxiosRequestConfig) => {
        const { method, url, params, data } = config;
        const controller = new AbortController();
        config.signal = controller.signal;
        const uniqueKey = [method, url, JSON.stringify(params), JSON.stringify(data)].join('&');
        this.pendingRequestList.set(uniqueKey, controller);
      };
    
     
      removePendingRequest(config: AxiosRequestConfig) {
        const { method, url, params, data } = config;
        const uniqueKey = [method, url, JSON.stringify(params), JSON.stringify(data)].join('&');
        if (this.pendingRequestList.has(uniqueKey)) {
          this.pendingRequestList.get(uniqueKey).abort();
          this.pendingRequestList.delete(uniqueKey);
        }
      }
    }
    
    4 replies    2022-11-09 10:40:23 +08:00
    RabbitDR
        1
    RabbitDR  
       Nov 8, 2022
    思路可能不太对,不应该基于 axios 去做这个工作。应该再加一层缓存,然后在缓存层去决定要不要发出一个 axios ,而不是去取消一个 axios ,这样无论你换什么请求工具都可以去重。具体可以参考 swr 的实现
    version0
        2
    version0  
       Nov 8, 2022
    我理解的 axios 的取消请求功能并不是真的取消了这次请求,因为发出去的请求是取消不了的,只是取消的请求没有 promise 回调而已
    hamsterbase
        3
    hamsterbase  
       Nov 9, 2022 via iPhone
    Function request(url)

    If(this.map.has(url
    Return this.map.url
    Else
    This.map.set(url, this.dorequest(url)
    )

    function dorequest(url
    // const res = await axios.get(url)
    This.map.delete(url)
    Return res

    手机打的伪代码。 核心是 request 和 dorequest 分离。
    在 request 实现缓存逻辑。
    wangerka
        4
    wangerka  
       Nov 9, 2022
    就楼上的缓存层,用 rxjs 的 switchMap 做吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4360 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 10:04 · PVG 18:04 · LAX 03:04 · JFK 06:04
    ♥ Do have faith in what you're doing.