Search code examples
javascriptjqueryes6-promise

Using a promise to wait for function called and finish doing what it suppose before continue


I am calling a function to load some file, this function is getting called from other places too..

for this section of code to run successfully searchconfig.js must load before

What I want to achieve is, for this call to finish loading searchconfig.js and just then continue with the other code and if error occurred, to log it:

loadRemoteFile("Search/" + Search.Configuration.PathToConfigurable + "/Configurable/searchconfig.js");

Full code:

$(document).ready(function () { 
    if (Search.Configuration && Search.Configuration.PathToConfigurable) {
        // the file that is necessary for the code to run successfully
        loadRemoteFile("Search/" + Search.Configuration.PathToConfigurable + "/Configurable/searchconfig.js");
    }

    setTimeout(function () {

        // anchor for injecting the  results
        $('body').prepend("<div id='search-results' class='container'></div>")

        for (var configItem in tempConfig) {
            Search.Configuration[configItem] = tempConfig[configItem];
        }

        var configsToCheckForSlash = ["FullPathToConfigurableFolder", "pathToSearch", "PathToConfigurable", "SearchServiceURL", "ThumbnailsURL", "CMSThumbnailsURL", "PreviewBaseURL"];

        for (var x = 0; x < configsToCheckForSlash.length; x++) {
            Search.Configuration[configsToCheckForSlash[x]] = addForwardSlashToSearchConfigSettings(Search.Configuration[configsToCheckForSlash[x]]);
            _log(Search.Configuration[configsToCheckForSlash[x]])
        }

        for (var x = 0; x < Search.Configuration.pagesToAvoid.length; x++) {
            var pagesToAvoid = Search.Configuration.pagesToAvoid[x].toLowerCase();
            if (location.href.toLowerCase().indexOf(pagesToAvoid) > -1) {
                _log("Search loader abandoned. Please check settings if this is not intended.");
                return;
            }
        }

        $("head").append(Search.Configuration.requiredFiles);

        //pick implementation points  
        Search.Configuration.anchorToUseForMainSearch = $("#search-results");

        if (!Search.Configuration.anchorToUseForMainSearch.length) {
            _log("The search implementation could not find a suitable place to place the search, aborting.");
            return;
        }

        searchIsExpanded = false;
        writeSearchHTML();
    }, 400);
});

loadRemoteFile function

function loadRemoteFile(filename, loadIntoHeader){ 
        filetype = filename.match(".css") ? "css" : "js";

        if (filetype=="js"){ 
            if(!loadIntoHeader){
                var script   = document.createElement("script");
                script.type  = "text/javascript";
                script.src   = filename;
                document.body.appendChild(script);          
            }else{
                ...             
            }           
        }else if (filetype=="css"){ 
            ...
        }
}

Solution

  • What i ended up using is to wait for the file loading.

    What I want to achieve is to finish loading searchconfig.js and just then continue with the other code:

     function when_external_loaded(callback) {
            // means searchconfig.js is loaded,
            // we should restrict the number of times we check 
            // if the parameter exist or restrict the max time for checking it
            if (typeof x.pagesToAvoid === 'undefined') {
                setTimeout(function () {
                    when_external_loaded(callback);
                }, 10); // wait 10 ms
            } else { callback(); }
        }
    

    and then in:

    (document).ready(function(){
        when_external_loaded(function () {
         // place all the code that you want to occur after the file has been loaded
        }
    });
    

    What will happen is Only when x.pagesToAvoid !== 'undefined') means that searchconfig.js was loaded, we it will load the function calls the callback function.

    Bear in mind that you should restrict the time of checking the file existing, cause if the file dont exist this will try forever (for me its OK, cause the existence of the file is not depend on nothing and he will be in that place).

    I didn't use the promise solution, cause i misunderstood something. the promise only return true if happen and false if not. So when the file was tried to load (but it didn't load yet to memory) the promise will be true.. and it wasn't enough for me.