axiosCancel.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import type { AxiosRequestConfig } from 'axios';
  2. // 用于存储每个请求的标识和取消函数
  3. const pendingMap = new Map<string, AbortController>();
  4. const getPendingUrl = (config: AxiosRequestConfig): string => {
  5. return [config.method, config.url].join('&');
  6. };
  7. export class AxiosCanceler {
  8. /**
  9. * 添加请求
  10. * @param config 请求配置
  11. */
  12. public addPending(config: AxiosRequestConfig): void {
  13. this.removePending(config);
  14. const url = getPendingUrl(config) +'_'+ new Date().getTime();
  15. const controller = new AbortController();
  16. config.signal = config.signal || controller.signal;
  17. if (!pendingMap.has(url)) {
  18. // 如果当前请求不在等待中,将其添加到等待中
  19. pendingMap.set(url, controller);
  20. }
  21. }
  22. /**
  23. * 清除所有等待中的请求
  24. */
  25. public removeAllPending(): void {
  26. pendingMap.forEach((abortController) => {
  27. if (abortController) {
  28. abortController.abort();
  29. }
  30. });
  31. this.reset();
  32. }
  33. /**
  34. * 移除请求
  35. * @param config 请求配置
  36. */
  37. public removePending(config: AxiosRequestConfig): void {
  38. const url = getPendingUrl(config);
  39. if (pendingMap.has(url)) {
  40. // 如果当前请求在等待中,取消它并将其从等待中移除
  41. const abortController = pendingMap.get(url);
  42. if (abortController) {
  43. abortController.abort(url);
  44. }
  45. pendingMap.delete(url);
  46. }
  47. }
  48. /**
  49. * 重置
  50. */
  51. public reset(): void {
  52. pendingMap.clear();
  53. }
  54. }