Skip to content

Instantly share code, notes, and snippets.

@legraphista
Last active July 11, 2024 18:40
Show Gist options
  • Save legraphista/f718eec899abddd41feb58829e3d4201 to your computer and use it in GitHub Desktop.
Save legraphista/f718eec899abddd41feb58829e3d4201 to your computer and use it in GitHub Desktop.
Dedupe racing promises by arguments
export class PromiseCacher<T extends (...args: any[]) => Promise<any>> {
private cache: Map<string, Promise<any>> = new Map();
private fn: T;
constructor(fn: T) {
this.fn = fn;
}
execute(...args: Parameters<T>): ReturnType<T> {
const key = JSON.stringify(args);
if (this.cache.has(key)) {
return this.cache.get(key) as ReturnType<T>;
}
const promise = this.fn(...args);
this.cache.set(key, promise);
promise.finally(() => {
this.cache.delete(key);
});
return promise as ReturnType<T>;
}
}
// example
const fetchPromiseCache = new PromiseCacher(async function fetcher(src: string) {
return await fetch(src);
});
const [a, b] = await Promise.all([fetchPromiseCache.execute('/hello'), fetchPromiseCache.execute('/hello')]);
console.log(a === b); // true
const [a2, b2] = await Promise.all([fetch('/hello'), fetch('/hello')]);
console.log(a2 === b2); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment