news 2026/1/11 6:04:45

Axios网络请求优化(缓存)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Axios网络请求优化(缓存)

合理使用缓存,避免重复请求

// 通过缓存机制,存储已经发出的请求结果,如果同样的请求再次发起, // 直接从缓存中获取数据,而不是重新发请求。 import axios from "axios"; // 缓存对象 const cache = new Map<string, any>(); // 封装带缓存的请求函数 async function axiosWithCache(url: string): Promise<any> { if (cache.has(url)) { console.log(`从缓存中获取数据: ${url}`); return cache.get(url); } console.log(`发送网络请求: ${url}`); const response = await axios.get(url); // 将结果存入缓存 cache.set(url, response.data); return response.data; } // 使用示例 (async () => { const url = "https://jsonplaceholder.typicode.com/todos/1"; const result1 = await axiosWithCache(url); // 第一次请求 console.log(result1); const result2 = await axiosWithCache(url); // 从缓存获取 console.log(result2); })();

使用 abortController 取消不再需要的请求。

// 当用户离开页面或切换视图时,取消掉未完成的请求以节省资源。 // 封装请求函数,支持 AbortController import axios from "axios"; // 封装带取消功能的请求函数 async function axiosWithAbort(url: string, controller: AbortController): Promise<any> { try { const response = await axios.get(url, { signal: controller.signal, // 绑定 AbortController 的 signal }); return response.data; } catch (error: any) { if (axios.isCancel(error)) { console.log(`请求已取消: ${url}`); } else { console.error("请求失败", error); } throw error; } } // 使用示例 (async () => { const controller = new AbortController(); const url = "https://jsonplaceholder.typicode.com/todos/1"; // 模拟请求 const fetchPromise = axiosWithAbort(url, controller); // 模拟用户取消请求 setTimeout(() => { controller.abort(); // 取消请求 }, 100); try { const result = await fetchPromise; console.log(result); } catch (error) { console.log("请求未完成,已被取消"); } })();
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2025/12/25 22:53:39

网络工程毕业设计容易的开题怎么做

文章目录&#x1f6a9; 1 前言1.1 选题注意事项1.1.1 难度怎么把控&#xff1f;1.1.2 题目名称怎么取&#xff1f;1.2 选题推荐1.2.1 起因1.2.2 核心- 如何避坑(重中之重)1.2.3 怎么办呢&#xff1f;&#x1f6a9;2 选题概览&#x1f6a9; 3 项目概览题目1 : 基于协同过滤的电影…

作者头像 李华
网站建设 2025/12/25 22:28:23

软件工程毕设易上手题目思路

1 引言 毕业设计是大家学习生涯的最重要的里程碑&#xff0c;它不仅是对四年所学知识的综合运用&#xff0c;更是展示个人技术能力和创新思维的重要过程。选择一个合适的毕业设计题目至关重要&#xff0c;它应该既能体现你的专业能力&#xff0c;又能满足实际应用需求&#xff…

作者头像 李华