当发送多个相同请求时,只会响应最后一次请求,效果如下。
创建CancelRequest.js文件
export default class CancelRequest {
pendings = []
constructor(CancelToken) {
this.CancelToken = CancelToken
}
getCancelToken(config) {
const { CancelToken } = this
return new CancelToken((cancel) => {
const { url, method } = config
const uKey = `${url}&${method}`
this.pendings.push({ uKey, cancel })// config.data为请求参数
})
}
removePending(config) {
const { url, method } = config
const { pendings } = this
const uKey = `${url}&${method}`
const findIndex = pendings.findIndex(p => p.uKey === uKey)
const pendingsLen = pendings.length
if (pendingsLen > 50) {
// 如果pendings存储数量大于50,则释放缓存
pendings.splice(0, pendingsLen - 2)
}
if (findIndex > -1) {
pendings[findIndex].cancel()
pendings.splice(findIndex, 1)
}
}
}
在axios中引入
// 主要代码
import CancelRequest from './CancelRequest'
const cancelRequest = new CancelRequest(axios.CancelToken)
// .....
service.interceptors.request.use(
config => {
/* -----------------------重复请求拦截------------------------- */
// requestConfig?.skipCancelRequest 对需要重复请求的情况做处理skipCancelRequest为true跳过(用不到可删除)
if (!requestConfig?.skipCancelRequest) {
cancelRequest.removePending(config)
config.cancelToken = cancelRequest.getCancelToken(config)
}
return config
}
)