自学内容网 自学内容网

vue 请求竞态 中断请求 解决切换表格数据,数据发生错乱


//1,声明缓存请求的集合
const pendingRequest = new Map();
//2,请求url和method生成key
const generateRequestKey = <T extends AxiosRequestConfig>(config: T) => {
const { method, url } = config
return [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.signal
pendingRequest.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)
})

原文地址:https://blog.csdn.net/Vue1024/article/details/142868451

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!