Deviopath › JavaScript

Memoize an Async Function

Hard · Async

Write memoizeAsync(fn, ttl). fn(key) returns a Promise. Return a function memo(key) that also returns a Promise and caches results per key.

- The first call for a key calls fn(key).

- While that call is still pending, more calls with the same key must not call fn again: they get the same result.

- A resolved value stays cached for ttl ms, counted from the moment it resolved. After that, the next call loads it again.

- If the call rejects, every caller waiting for it gets the rejection and nothing is cached: the next call tries again.

testMemo(ops, failOnce) is already written. Its loader takes 20ms, fails the first load of every key in failOnce, and resolves to the key in uppercase plus the load number ("A#2"). ttl is 60. It returns each call's result and the total number of loads.

Next: Text Justification