Files
pokemon-showdown-client/lib/async-cache.ts
Guangcong Luo 36ba1106bb
Some checks failed
Node.js CI / build (24.x) (push) Has been cancelled
Migrate static pages to AstralHP
We're serving exactly one dynamic endpoint as a test. If it works, I'll
start migrating dynamic pages and we'll see how it goes!

Because I can't resist making at least a few changes whenever I do
things like this, this also:
- adds dark mode support to our static pages
- adds better link styling to our static pages
2026-11-23 13:10:30 +09:00

25 lines
640 B
TypeScript

export class AsyncCache<T> {
private readonly ttlMs: number;
private readonly load: () => Promise<T>;
private cached?: { value: T, expires: number };
private loading?: Promise<T>;
constructor(ttlMs: number, load: () => Promise<T>) {
this.ttlMs = ttlMs;
this.load = load;
}
async get(): Promise<T> {
if (this.cached && Date.now() < this.cached.expires) return this.cached.value;
if (this.loading) return this.loading;
this.loading = this.load();
try {
const value = await this.loading;
this.cached = { value, expires: Date.now() + this.ttlMs };
return value;
} finally {
this.loading = undefined;
}
}
}