需求場景:對同一時間發起的大量重複引數相同的請求做快取,但是在過了幾秒鐘之後就不需要快取了,需要重新向伺服器請求最新的資料
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
}
}