Search code examples
javascriptlodashmemoization

Does Javascript memoize Cache Between Imports?


Using the example below for Lodash memoize, my understanding is that otherModule.js will use the cached version fetched from data when fetching for data2, but will it also use the cached version for data within otherModule2.js if it was previously fetched/cached by otherModule.js? And if not is there a way to make it so the two modules share the same cache?

// getData.js
import _ from 'lodash';
const dataPromise(url) = async fetch(url).then(value => value.json());
export const memDataPromise = _.memoize(dataPromise);

// otherModule.js
import { dataPromise } from './getData.js';
const data = await dataPromise('someUrl');
const data2 = await dataPromise('someUrl');

// OtherModule2.js
import { dataPromise } from './getData.js';
const data = await dataPromise('someUrl');

Solution

  • Yes, the top level of a module will run exactly once, no matter how many times it's imported. You'll see that if you, for example, put a console.log statement inside a module, that log will only occur once.

    The first time a module is imported, a namespace object corresponding to the module is created, the module's top-level code runs, and the module's exports are assigned to that namespace. When the module is imported in the future, the already-existing namespace is simply referenced again.