mercredi 19 août 2020

JavaScript module dependent on results of an Async functions return value

Below is a very common module pattern for me, the difference in this particular module i'm trying to build is that there is a dependency on the value returned by a REST API call. What might be the proper approach to wiring this code so that "siteinfo" is available to other functions in the module, as well as calling functions in the module.

mod1.getSiteInfo() returns the correctly value, just not immediately.

(function (ns) {
    var siteinfo;
    
    jQuery.getJSON(location.href + '/_api/site')
    .then( function(data) {
        siteinfo = data; 
    });

    ns.getSiteInfo = function() {        
        return siteinfo
    }

    // TODO: need to write a dozen other methods that rely on ns.siteinfo having proper data from the API call.

}(window.mod1 = window.mod1 || {}));

// and how to know that getSiteInfo will provide me the value i expect from the API Call? 
console.log(mod1.getSiteInfo());

Aucun commentaire:

Enregistrer un commentaire