mirror of
https://github.com/smogon/pokemon-showdown-client.git
synced 2026-11-24 23:06:40 -06:00
Some checks failed
Node.js CI / build (24.x) (push) Has been cancelled
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
25 lines
640 B
TypeScript
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;
|
|
}
|
|
}
|
|
}
|