实现思路
- 创建缓存对象:用于存储请求的缓存数据。
- 记录缓存时间:为每个缓存数据记录缓存时间,以便判断缓存是否过期。
- 封装请求函数:在原有网络请求函数基础上,每次请求前先检查缓存中是否有对应数据且未过期,若有则直接返回缓存数据,否则发起新请求并更新缓存。
关键代码
// 假设已有网络请求函数,例如:
const httpRequest = async (url, method = 'GET', data = null) => {
// 实际的网络请求逻辑
const response = await fetch(url, {
method,
headers: {
'Content-Type': 'application/json'
},
body: data ? JSON.stringify(data) : null
});
return response.json();
};
// 创建缓存对象
const requestCache = {};
// 封装带有缓存功能的请求函数
const cachedHttpRequest = async (url, method = 'GET', data = null, cacheTime = 5 * 1000) => {
const cacheKey = `${url}-${method}-${JSON.stringify(data)}`;
const cached = requestCache[cacheKey];
if (cached && Date.now() - cached.timestamp < cacheTime) {
return cached.data;
}
const response = await httpRequest(url, method, data);
requestCache[cacheKey] = {
data: response,
timestamp: Date.now()
};
return response;
};