35 lines
723 B
TypeScript
35 lines
723 B
TypeScript
|
|
export default class CachePromise<DataType = any> {
|
||
|
|
expireTime: number;
|
||
|
|
curTm: number = 0;
|
||
|
|
promise: Promise<DataType> | undefined;
|
||
|
|
pf: () => Promise<DataType>;
|
||
|
|
|
||
|
|
constructor(pf: () => Promise<DataType>, expireTime?: number) {
|
||
|
|
this.pf = pf;
|
||
|
|
this.expireTime = expireTime || 0;
|
||
|
|
}
|
||
|
|
|
||
|
|
setNull = () => {
|
||
|
|
this.promise = undefined;
|
||
|
|
}
|
||
|
|
|
||
|
|
get = async () => {
|
||
|
|
const now = Date.now();
|
||
|
|
if (this.expireTime && now - this.curTm > this.expireTime) {
|
||
|
|
this.promise = this.pf();
|
||
|
|
this.curTm = now;
|
||
|
|
}
|
||
|
|
if (!this.promise) {
|
||
|
|
this.promise = this.pf();
|
||
|
|
this.curTm = now;
|
||
|
|
}
|
||
|
|
|
||
|
|
const data = await this.promise;
|
||
|
|
if (!data) {
|
||
|
|
this.setNull();
|
||
|
|
}
|
||
|
|
|
||
|
|
return data;
|
||
|
|
}
|
||
|
|
}
|