2

给lodash的memoize 增加expire过期功能

 2 years ago
source link: https://segmentfault.com/a/1190000040951697
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

给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);
  };
};
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...


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK