xf-web/src/utils/cachepromise.ts

35 lines
723 B
TypeScript
Raw Normal View History

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;
}
}