Skip to content

Instantly share code, notes, and snippets.

@nrkn
Created February 23, 2024 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nrkn/1bd85b384cf86c35faf30ec54535ba44 to your computer and use it in GitHub Desktop.
Save nrkn/1bd85b384cf86c35faf30ec54535ba44 to your computer and use it in GitHub Desktop.
Shared promises, simpler version of cached-promises
export type ToSlugFunction<T extends any[]> = (...args: T) => string
export const sharedPromiseCache = <T extends any[], R>(
fn: (...args: T) => Promise<R>,
toSlug: ToSlugFunction<T> = (...args: T) => JSON.stringify(args)
): ((...args: T) => Promise<R>) => {
const cache = new Map<string, Promise<R>>()
return async (...args: T): Promise<R> => {
const key = toSlug(...args)
if (cache.has(key)) {
// Return the existing promise if found in the cache
return cache.get(key)!
}
// Wrap the original function call in a promise to manage its lifecycle
const promise = (async () => {
try {
// Call the original function with the arguments
return await fn(...args)
} finally {
// Remove from cache when the promise is settled (resolved or rejected)
cache.delete(key)
}
})()
// Store the promise in the cache before returning it
cache.set(key, promise)
return promise
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment