Created
December 10, 2025 21:36
-
-
Save joncardasis/5f49ff0e9085817afc4eb97920e74013 to your computer and use it in GitHub Desktop.
Memoize an async function, caching the resolved value and deduplicate concurrent calls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** 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