博客 / 詳情

返回

給lodash的memoize 增加expire過期功能

需求場景:對同一時間發起的大量重複參數相同的請求做緩存,但是在過了幾秒鐘之後就不需要緩存了,需要重新向服務器請求最新的數據

lodash.memoize方法會在整個頁面的生命週期。需要增加一個超時功能

思路:類似於防抖函數,每次判斷是否超過設置時間,超過就清空緩存列表

const myMemoize = (fn, duration = 2000) => {
  let t = new Date().getTime();
  const memoized = _.memoize(fn, (...args) => JSON.stringify(args));
  return (...args) => {
    const curr = new Date().getTime();
    if (curr - t > duration) {
      memoized.cache = new _.memoize.Cache();
      t = curr;
    }
    return memoized(...args);
  };
};

ts版

export const myMemoize = <T extends (...args: any[]) => Promise<any>, R = ReturnType<T>>(fn: T, duration = 2000) => {
  let t = new Date().getTime()
  const memoized = memoize(fn,(...args: Parameters<T>) => JSON.stringify(args))
  return (...args: Parameters<T>) => {
    const curr = new Date().getTime()
    if(curr - t > duration) {
      memoized.cache = new memoize.Cache
      t = curr
    }
    return memoized(...args) as unknown as R
  }
}

例子 https://stackblitz.com/edit/m...

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.