axiosCancel.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import type { AxiosRequestConfig, Canceler } from 'axios'
  2. import axios from 'axios'
  3. import { isFunction } from '@/utils/is'
  4. // 用于存储每个请求的标识和取消功能
  5. let pendingMap = new Map<string, Canceler>()
  6. export const getPendingUrl = (config: AxiosRequestConfig) => [config.method, config.url].join('&')
  7. export class AxiosCanceler {
  8. /**
  9. * 添加请求
  10. * @param {Object} config
  11. */
  12. addPending(config: AxiosRequestConfig) {
  13. this.removePending(config)
  14. const url = getPendingUrl(config)
  15. config.cancelToken =
  16. config.cancelToken ||
  17. new axios.CancelToken((cancel) => {
  18. if (!pendingMap.has(url)) {
  19. // If there is no current request in pending, add it
  20. pendingMap.set(url, cancel)
  21. }
  22. })
  23. }
  24. /**
  25. * @description: 清除所有待处理的
  26. */
  27. removeAllPending() {
  28. pendingMap.forEach((cancel) => {
  29. cancel && isFunction(cancel) && cancel()
  30. })
  31. pendingMap.clear()
  32. }
  33. /**
  34. * 删除请求
  35. * @param {Object} config
  36. */
  37. removePending(config: AxiosRequestConfig) {
  38. const url = getPendingUrl(config)
  39. if (pendingMap.has(url)) {
  40. // 如果挂起中有当前请求标识符,则需要取消并删除当前请求
  41. const cancel = pendingMap.get(url)
  42. cancel && cancel(url)
  43. pendingMap.delete(url)
  44. }
  45. }
  46. /** 重置 */
  47. reset(): void {
  48. pendingMap = new Map<string, Canceler>()
  49. }
  50. }