Open shfshanyue opened 3 years ago
promise.all 或者 async await
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));