同一页面三个组件请求同一个 API 发送了三次请求,如何优化
Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 642
Author 回答者: shfshanyue
const fetchUser = (id) => {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Fetch: ", id);
resolve(id);
}, 5000);
});
};
const cache = {};
const cacheFetchUser = (id) => {
if (cache[id]) {
return cache[id];
}
cache[id] = fetchUser(id);
return cache[id];
};
cacheFetchUser(3).then((id) => console.log(id))
cacheFetchUser(3).then((id) => console.log(id))
cacheFetchUser(3).then((id) => console.log(id))
// Fetch: 3
// 3
// 3
// 3
Author 回答者: juvenile-spec
promise.all 或者 async await
Author 回答者: juvenile-spec
const fetchUser = (id) => { return new Promise(resolve => { setTimeout(() => { console.log(‘Fetch: ’, id) resolve(id) }, 5000) }) }
const cache = new Map(); // 使用 Map 替代对象
const cacheFetchUser = (id) => { if (cache.has(id)) { const { data, timestamp } = cache.get(id); const currentTime = new Date().getTime(); const expirationTime = 60000; // 过期时间为 1 分钟 if (currentTime - timestamp < expirationTime) { return Promise.resolve(data); // 返回缓存的数据 } else { cache.delete(id); // 清除过期的缓存数据 } }
const fetchData = fetchUser(id) .then(data => { cache.set(id, { data, timestamp: new Date().getTime() }); // 将数据存入缓存 return data; });
cache.set(id, { data: fetchData, timestamp: new Date().getTime() }); // 将 Promise 存入缓存 return fetchData; }
// 示例使用 cacheFetchUser(3).then((id) => console.log(id)); cacheFetchUser(3).then((id) => console.log(id)); cacheFetchUser(3).then((id) => console.log(id));