axios请求缓存与重复拦截:“相同请求未完成时,不发起新请求”
import axios from "axios";// 1. 缓存已完成的请求结果(key:请求URL+参数,value:数据)
const requestCache = new Map();
// 2. 记录正在执行的请求(避免并行重复请求)
const pendingRequests = new Set();// 请求拦截器:发起请求前检查
axios.interceptors.request.use(config => {// 生成请求唯一标识(URL + 方法 + 参数)const requestKey = `${config.url}-${config.method}-${JSON.stringify(config.params)}`;// 情况1:请求正在执行中,拦截新请求if (pendingRequests.has(requestKey)) {return Promise.reject(new Error("当前请求已在执行,请勿重复触发"));}// 情况2:请求已缓存,直接返回缓存数据(不发新请求)if (requestCache.has(requestKey)) {return Promise.resolve({ data: requestCache.get(requestKey) });}// 情况3:新请求,加入“正在执行”列表pendingRequests.add(requestKey);return config;
});// 响应拦截器:请求完成后更新缓存/状态
axios.interceptors.response.use(response => {const requestKey = `${response.config.url}-${response.config.method}-${JSON.stringify(response.config.params)}`;// 1. 缓存请求结果requestCache.set(requestKey, response.data);// 2. 从“正在执行”列表移除pendingRequests.delete(requestKey);return response;},error => {// 错误时也移除“正在执行”状态const requestKey = `${error.config.url}-${error.config.method}-${JSON.stringify(error.config.params)}`;pendingRequests.delete(requestKey);return Promise.reject(error);}
);// 调用示例:相同参数的请求,短时间内只发一次
function fetchStyle() {axios.get("/api/page-style", { params: { theme: "light" } }).then(res => console.log("样式数据(缓存/新请求):", res.data)).catch(err => console.log("请求拦截:", err.message));
}// 1秒内调用3次,只发1次请求,后2次用缓存
fetchStyle();
setTimeout(fetchStyle, 500);
setTimeout(fetchStyle, 800);
这个地方的set和map使用,为什么不用对象和数组?
- 用普通对象 {} 替代 Map:
可行,但键只能是字符串 / Symbol,且判断键是否存在需要用 obj.hasOwnProperty(key)(不如 map.has(key) 直观)。 - 用数组 [] 替代 Set:
可行,但检查是否存在需要 array.includes(key)(O (n) 复杂度,数据量大时效率低),且需要手动去重(if (!array.includes(key)) array.push(key))。