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

Wait for module loaded state

The old wait for data to be loaded thing.

I have a module that uses asynch request to load data from local storage.

The scripts that uses this module have to wait for it to load the data before initializing.

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

I can use something like this (Here a dummy function that "sleeps" for 1 second), two files in one sample:

// data.js: The wait for it module
const load_things = new Promise(resolve => {
    setTimeout(()=> resolve(), 1000);
});
const load = async () => {
    await load_things;
    return true;
};
const data = {
    load: load(),
    foo: () => { /* something else from this module */ }
};
// export {data};

// ====================================================

// user.js: The script using the module
// import {data} from 'data.js';

const init = async () => {
    const ready = await data.load;
    console.log('Proceed:', ready);
    // use the data module
};

init();

It feels a bit wonky and one are left with a Promise instead of a simple boolean on the data object.

My question is if this way of doing it is way off or something else?

I pondered about using Event and fire that from the data.js module, but issue with that is if the Event is fired before any user script has added a listener. One could of course add a property like loaded: true|false to the exported object and do something like:

if (data.loaded === false)
    foo.addEventListener('dataLoaded', init)
else
    init()

But not sure if that is a better approach. It leaves more to the user script. A simple await or .then() is a bit cleaner, or? Not sure.

>Solution :

Export a loader (the thing that loads, not the loaded thing). Use it right after import.

// data.js: The "you can't wait for it" module
const load_things = new Promise(resolve => {
    setTimeout(()=> resolve(), 1000);
});
const loader = async () => {
    await load_things;
    return true;
};
export default {
    loader: loader,  // mention it, don't invoke it
    foo: () => { /* something else from this module */ }
};

The importer says:

import object from 'data.js'

object.loader().then(data => {
  // use data and object
})
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