HomeToolsAbout

Caching and Memoization (JS)

What is it

Function expects a passing of async_method.

  • Any async function that will take an argument.

cache variable is a cache recording registry.

  • Each record consists of key that is a stringified version of arguments passed to the method.
  • value that is a Promise (not yet awaited) that calls the async function with the given arguments.

We are caching the promise returned by the method, not the final value.

function memoize(async_method) { let cache = {}; return async function() { let args = JSON.stringify(arguments); // store promise (before awaiting) as value cache[args] = cache[args] || async_method.apply(this, arguments); return cache[args]; }; }

How to use it:

const getSomeDataMemoized = memoize(async function() { return await fetch("/api/someRoute", { method: "GET", }); }); const getAnotherRequestMemoized = memoize(async function() { return await fetch("/api/otherRequest", { method: "GET", }); }); const materFunction = memoize(async function() { const [result1, result2] = await Promise.all([ getSomeDataMemoized(), getAnotherRequestMemoized() ]); return result1; });
AboutContact