Memoize Async Function Results
Memoize Async Function Results is a reusable JavaScript snippet. Caches the results of async function calls in memory. Prevents redundant network requests for the same arguments. The full implementation: function memoizeAsync(fn, ttlMs = null) { const cache = new Map() const pending = new Map() // Dedup concurrent calls return async function(...args) { const key = JSON.stringify(args) // Check cache if (cache.has(key)) { const entry = cache.get(key) if (!ttlMs || Date.now() { cache.set(key, { data, expiry: ttlMs ? Date.now() + ttlMs : Infinity }) pending.delete(key) return data }).catch(err => { pending.delete(key) throw err }) pending.set(key, promise) return promise } } // Usage const fetchUser = memoizeAsync(async (id) => {… This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.