//1,声明缓存请求的集合
const pendingRequest = new Map();
//2,请求url和method生成key
const generateRequestKey = <T extends AxiosRequestConfig>(config: T) => {const { method, url } = configreturn [method, url].join("&")
}
//3,缓存正在pending状态的请求
const addPendingRequest = (config: AxiosRequestConfig) => {const requestKey = generateRequestKey(config)// 判断是否正在pending中if (pendingRequest.has(requestKey)) {const controller = pendingRequest.get(requestKey)//终止请求controller.abort()pendingRequest.delete(requestKey)}// 添加请求const controller = new AbortController()config.signal = controller.signalpendingRequest.set(requestKey, controller)
}
// 4,删除缓存的请求
const removePendingRequest = (config: AxiosRequestConfig) => {const requestKey = generateRequestKey(config)if (pendingRequest.has(requestKey)) {pendingRequest.delete(requestKey)}
}
在请求拦截器里添加
// 添加请求拦截器
service.interceptors.request.use((config) => {addPendingRequest(config)// 在发送请求之前做些什么return config;
}, function (error) {// 对请求错误做些什么return Promise.reject(error);
});
在响应拦截器里移除
// 添加响应拦截器
service.interceptors.response.use((response: any) => {removePendingRequest(response.config)
})