Skip to content

Commit 6799dd1

Browse files
committed
perf: 添加超时设置
1 parent b4895ea commit 6799dd1

1 file changed

Lines changed: 24 additions & 6 deletions

File tree

src/background/utils.ts

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,16 +52,34 @@ export type MyRankingType = {
5252
my_rank: RankType
5353
}
5454

55+
/**
56+
* 根据 key 缓存函数执行结果
57+
* @param keyFn 生成缓存的 key
58+
* @param handle 输出函数
59+
* @param timeout 超时设置,单位为毫秒,默认为 10 分钟,如果缓存数据超过 timeout,则重新获取结果
60+
* @returns
61+
*/
5562
function cache<T extends any[], R>(
5663
keyFn: (...args: T) => string,
57-
fn: (...args: T) => Promise<R>
64+
handle: (...args: T) => Promise<R>,
65+
timeout = 600000
5866
): (...args: T) => Promise<R> {
59-
const map = new Map<string, Promise<R>>()
60-
return (...args: T) => {
67+
const map = new Map<string, [Promise<R>, number]>()
68+
return async (...args: T) => {
6169
const key = keyFn(...args)
62-
if (map.has(key)) return map.get(key)!
63-
const promise = fn(...args)
64-
map.set(key, promise)
70+
if (map.has(key)) {
71+
const [promise, time] = map.get(key)!
72+
if (new Date().valueOf() - time <= timeout) {
73+
try {
74+
const data = await promise
75+
return data
76+
} catch (error) {
77+
// 如果当前缓存有错误,则舍弃缓存的结果,重新获取
78+
}
79+
}
80+
}
81+
const promise = handle(...args)
82+
map.set(key, [promise, new Date().valueOf()])
6583
return promise
6684
}
6785
}

0 commit comments

Comments
 (0)