You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.5 KiB

2 years ago
import type { InternalAxiosRequestConfig, Canceler } from 'axios'
import axios from 'axios'
import { isFunction } from '@/utils/is'
// Used to store the identification and cancellation function of each request
let pendingMap = new Map<string, Canceler>()
export const getPendingUrl = (config: InternalAxiosRequestConfig) => [config.method, config.url].join('&')
export class AxiosCanceler {
/**
2 years ago
*
2 years ago
* @param {Object} config
*/
addPending(config: InternalAxiosRequestConfig) {
this.removePending(config)
const url = getPendingUrl(config)
config.cancelToken =
config.cancelToken ||
new axios.CancelToken((cancel) => {
if (!pendingMap.has(url)) {
2 years ago
// 如果当前没有待处理的请求,添加它
2 years ago
pendingMap.set(url, cancel)
}
})
}
/**
2 years ago
* @description:
2 years ago
*/
removeAllPending() {
pendingMap.forEach((cancel) => {
cancel && isFunction(cancel) && cancel()
})
pendingMap.clear()
}
/**
2 years ago
*
2 years ago
* @param {Object} config
*/
removePending(config: InternalAxiosRequestConfig) {
const url = getPendingUrl(config)
if (pendingMap.has(url)) {
2 years ago
// 如果有当前请求标识符处于pending状态,则需要取消当前请求并移除
2 years ago
const cancel = pendingMap.get(url)
cancel && cancel(url)
pendingMap.delete(url)
}
}
/**
* @description: reset
*/
reset(): void {
pendingMap = new Map<string, Canceler>()
}
}