Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading