promise-cache.ts 456 B

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