]>
Commit | Line | Data |
---|---|---|
1 | export class PromiseCache <A, R> { | |
2 | private readonly running = new Map<string, Promise<R>>() | |
3 | ||
4 | constructor ( | |
5 | private readonly fn: (arg: A) => Promise<R>, | |
6 | private readonly keyBuilder: (arg: A) => string | |
7 | ) { | |
8 | } | |
9 | ||
10 | run (arg: A) { | |
11 | const key = this.keyBuilder(arg) | |
12 | ||
13 | if (this.running.has(key)) return this.running.get(key) | |
14 | ||
15 | const p = this.fn(arg) | |
16 | ||
17 | this.running.set(key, p) | |
18 | ||
19 | return p.finally(() => this.running.delete(key)) | |
20 | } | |
21 | } |