shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.92k stars 510 forks source link

【Q624】同一页面三个组件请求同一个 API 发送了三次请求,如何优化 #642

Open shfshanyue opened 3 years ago

shfshanyue commented 3 years ago
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 
juvenile-spec commented 6 months ago

promise.all 或者 async await

juvenile-spec commented 6 months ago

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));