0

I have looked and looked and I am still scratching my head. If I have missed something obvious, I apologise. I have tried to create a custom library of functions that I have written myself (thanks stackoverflow for helping me work that one out....). I then have a javascript file that loads when the web page is called, which in turn calls said functions in my custom library.

I have a function called getConfig() that does the obvious. It gets a JSON file with the configuration details for my server that hosts all of my RESTful web services. When I step through the code, the configuration details are returning as I would expect, however, when I load the web page at full speed, the configuration object comes back as undefined. I thought it might be a timing thing, so I wrapped everything in a $(document).ready(function()) block, but no go. I even tried a window.onload = function(){} block to make sure everything is loaded before the custom libraries are called. No luck! Its doing my head in as I cannot for the life of me work out what is going on.

My custom library file looks like this with filename xtendLibs.js

var xtendLibs = {
    getConfig           :   function(){

        var CONFIG;

        $.getJSON("/js/config.json", function(json){
            CONFIG = json;
        });
        return CONFIG;
    },
    getObjects          :   function(config, medicareno, medicarelineno, objectType){

        var object;

        var urlString = config.scheme + config.muleHost + config.mulePort + ":/patients/";

        switch(objectType){
            case ("details") : 
                urlString = urlString + "details/" + medicareno + "/" + medicarelineno ;
                break;
            case ("appointments") :
                urlString = urlString + "appointments/" + medicareno +"/" + medicarelineno;
                break;
        }

        $.ajax({
            type    :   'GET',
            url     :   urlString,
            success :   function(data){
                object = data;
            },
            failure :   function(){
                alert("Failure");
            }
        });
        return object;
    },
    getUrlParameters    :   function(){
        var paramsArray = window.location.search.substring(1).split("&");
        var obj = [];
        var tempArray;
        var paramName,paramValue;

        for(var i = 0; i < paramsArray.length; i++){
            tempArray = paramsArray[i].split("=");
            paramName = tempArray[0];
            paramValue = tempArray[1];
            obj[paramName] = paramValue;
        }

        return obj;
    }

};

The javascript file that calls the various functions in the above file looks like this appts.js

window.onload = function(){

    var config, params, appointments;

    params = xtendLibs.getUrlParameters();   // This line works - and params is returned

    config = xtendLibs.getConfig(); // This line fails but will work if I step through the code

    appointments = xtendLibs.getObjects(    config, 
                                            params["medicareno"],
                                            params["medicarelineno"],
                                            "appointments");

    console.log(params);
}

I am truly stumped. Any help would be greatly appreciated.

  • any console.log errors? – Sandra Willford Feb 10 '18 at 05:54
  • In your HTML what is the order with which you are mentioning these `js` files? – Sudheesh Singanamalla Feb 10 '18 at 05:56
  • This looks to be an issue with your understanding of how asynchronous calls work. The problem is you're trying to return the config before it has loaded. Hence the code works when you step through it but not when you run it normally. Have a look at this answer https://stackoverflow.com/a/133327/242311 for example. – Nicholas Sizer Feb 10 '18 at 06:01
  • Thanks everyone for your answers. Its true, I am struggling with the async component of Javascript. Its foreign to me. Ive sat through a number of courses on Udemy, but the async component doesn't get discussed. There are a couple of good links here that I will read though. I apologise for asking such a newbie question. Cheers!! – Darren Smith Feb 11 '18 at 03:13

1 Answers1

0

Ajax is async process, so when getJson is called it does not stop the execution of next statement.

getConfig : function(){

     var CONFIG;

     $.getJSON("/js/config.json", function(json){
          CONFIG = json;
     });
     return CONFIG;
}

When getJson is called it switches to a new thread, and the next statement which is in this case is "return CONFIG;" is executed. However, CONFIG has not been defined yet, so it is returning as undefined.

How Could you solve this problem?

You could not solve this problem. Not using this code design. You could non async the ajax, but it will make your page freeze.

You could set a global variable "config" when "getConfig" is called and check whether the config variable is defined when executing any function concerning it, but the best approach would be to pass a function, containing all the statements to be executed when config has finished loading, in getConfig function and call it when "/js/config.json" has loaded.

Ashish Kumar
  • 186
  • 3