← JavaScript Coding

Memoize Async Function

hardpromisesmemoizationcache
Asked at
GitHub
LinkedIn
Meta
Notion
Shopify
Vercel
GitHub, LinkedIn, Meta, Notion, Shopify, Vercel

Problem statement

Implement memoizeAsync(fn, options). It should cache async function results by argument key.

Requirements

  • Calls with the same key while the first call is pending should share the same in-flight promise.
  • Resolved values should be cached until ttl milliseconds pass.
  • Rejected promises should not poison the cache by default.
  • Support a custom getKey(...args) function.
  • Expose clear() to empty the cache.

This question is popular in senior frontend screens because it tests async race conditions, cache invalidation, and duplicate request prevention.

Requirements & constraints

  • →Concurrent same-key calls should call the underlying function only once.
  • →Expired entries should be replaced.
  • →Expose a `clear` method on the returned function.

How to approach Memoize Async Function

The strategy an interviewer expects you to reach for.

Async memoization caches promises so concurrent identical calls share one in-flight request — not just the final value. Naive move Cache resolved values only. Two overlapping calls both hit the network before either stores a result. Where it breaks Thundering herd on cold cache. Rejected promises may poison the cache if you keep them forever. TTL must expire stale entries. The fix Map key → {promise, expiresAt}. On hit with fresh TTL, return the same promise. On miss, start fn, store the promise immediately, optionally delete on reject. Remember: Cache the promise, not only the value — that collapses concurrent duplicates. Say this in the interview: I'd memoize the in-flight promise under a key, reuse it for concurrent callers, and expire entries with a TTL so stale data cannot live forever.

Premium

The full solution is part of HelloFrontend Pro

The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.

  • Runnable editor with the hidden test suite
  • Progressive hints that unlock as you get stuck
  • Senior-level reference solution with a line-by-line walkthrough
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingEasy

City Fetcher API

JS CodingHard

promise.all( )

JS CodingHard

promise.allSettled( )

JS CodingHard

promise.any( )

JS CodingHard

promise.race( )

JS CodingEasy

promise.reject()

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub
  • GitHub interview
  • LinkedIn interview
  • Meta interview
  • Notion interview
  • Shopify interview
  • Vercel interview