Skip to content

Instantly share code, notes, and snippets.

@joncardasis
Created December 10, 2025 21:36
Show Gist options
  • Select an option

  • Save joncardasis/5f49ff0e9085817afc4eb97920e74013 to your computer and use it in GitHub Desktop.

Select an option

Save joncardasis/5f49ff0e9085817afc4eb97920e74013 to your computer and use it in GitHub Desktop.
Memoize an async function, caching the resolved value and deduplicate concurrent calls
/** Memoizes an async function, caching the resolved value and deduplicating concurrent calls */
export const memoizePromise = <T>(fn: () => Promise<T>): (() => Promise<T>) => {
let cached: T
let hasCached = false
let pending: Promise<T> | null = null
return () => {
if (hasCached) {
return Promise.resolve(cached)
}
if (!pending) {
pending = fn().then(value => {
cached = value
hasCached = true
pending = null
return value
})
}
return pending
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment