axios请求缓存与重复拦截:“相同请求未完成时,不发起新请求”

javascript 复制代码
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使用,为什么不用对象和数组?

  1. 用普通对象 {} 替代 Map:
    可行,但键只能是字符串 / Symbol,且判断键是否存在需要用 obj.hasOwnProperty(key)(不如 map.has(key) 直观)。
  2. 用数组 \[\] 替代 Set:
    可行,但检查是否存在需要 array.includes(key)(O (n) 复杂度,数据量大时效率低),且需要手动去重(if (!array.includes(key)) array.push(key))。
相关推荐
星栈10 小时前
Dioxus 多页面怎么做:`dioxus-router`、嵌套路由、`Outlet` 和页面组织,一篇给你讲顺
前端·rust·前端框架
用户9874092388710 小时前
用 Remotion + edge-tts 打造中文教学视频全自动流水线
前端
风骏时光牛马10 小时前
Less前端工程化实战:变量混合器与项目样式分层落地
前端
假如让我当三天老蒯10 小时前
Options API(选项式 API) 和 Composition API(组合式 API)
前端·vue.js·面试
SameX10 小时前
iOS 独立开发实践:用 MapKit + 像素渲染实现 Citywalk 轨迹地图 App「雁过留痕」
前端
skyey10 小时前
页面加载时,深色模式闪白的问题解决
前端
IT_陈寒11 小时前
Java 并行流把我坑惨了,这6小时加班值了
前端·人工智能·后端
anOnion20 小时前
构建无障碍组件之Menu Button pattern
前端·html·交互设计
用户479492835691520 小时前
claude Fable用不了?把Gpt 5.5pro接到你的claude code里
前端·后端
zhangxingchao1 天前
Kotlin常用的Flow 操作符整理
前端