Search code examples
javascriptfunctionreturn

Function returns before variable is defined


I have a simple series of functions :

    convertXML();

    function convertXML(){

        var xmlObj = xmlToJson(xml.responseXML)
            .query.results.WMS_Capabilities;
        console.log("convertXML");

        (function checkReturn(){
            if(typeof xmlObj != 'undefined'){
            return (function(){ return createData(xmlObj)})();
            }
            else {
                setTimeout(checkReturn, 50);
            }
        })();
    }

    function createData(xmlObj){
        for (var i = 0; i < xmlObj.Capability.Layer.Layer.length; i++){
            var row={};
            row = xmlObj.Capability.Layer.Layer[i];
            WMSLayers.push(row);
        };
        console.log("createdata",WMSLayers)

        return (function(){return finish()})();
    }

    function finish(){
        console.log(n == Server.length-1)
        if (n == Server.length-1){
            //n is defined as an argument
            //this code is a part of a bigger function
            //same for Server variable
                createTable();

            };
    }

The problem is that that the convertXML function sometimes returns the callback function createData with the xmlObj variable undefined. So I have to check if the variable is defined to call the callback function.

My question is isn't a function suppose to return when all its variables are finished loading data?

UPDATE

This is how I make the request:

var req = {
    "type"    :"GET",
    "dataType":"XML",
    "data"    : null,
    "url"     : url
};

//make the request (ajax.js)
ajax(req,ajaxSuccess,ajaxError);

function ajax(prop,onsuccess,onerror){
// data = data || null;
// var url = "wps"; // the script where you handle the form input.

$.ajax({
    type: prop.type,
    dataType: prop.dataType,
    data: prop.data,
    url: prop.url,
    success: function (data, textStatus, xhr) {
        console.log(xhr)
        onsuccess(xhr);
    },
    error:function (data ,textStatus, xhr) {
        onerror(xhr);
    }

});
// e.preventDefault();
}

function ajaxSuccess(xhr){
    $("#messages").append(
        '<span style="color:blue">' +
        getFullTime() + 
        '</span> Response HTTP status <b>' + 
        xhr.status + 
        ' [' + xhr.statusText + ']' +
        '</b> from:' +
        ' <a style="color:grey;text-decoration:none;" href="' +
        url+
        '" target="_blank">'+
        Server[i].link + 
        Request["getCapabilities"]+
        '</a><br>'
    );

    //create the wms
    createWMS(xhr, Server[i],i);//this is where the convertXML,createData and finish functions are located

        };

Solution

  • You can use the complete function of $.get(). Note, n does not appear to be defined within finish function.

    function convertXML(xml, textStatus, jqxhr) {
      var xmlObj = xmlToJson(jqxhr.responseXML)
                   .query.results.WMS_Capabilities;
      console.log("convertXML");
    
      if (typeof xmlObj != 'undefined') {
          createData(xmlObj);
      }
    }
    
    function createData(xmlObj){
      for (var i = 0; i < xmlObj.Capability.Layer.Layer.length; i++){
          var row = xmlObj.Capability.Layer.Layer[i];
          WMSLayers.push(row);
       };
       console.log("createdata",WMSLayers)
       finish();
    }
    
    $.get("/path/to/resource",  convertXML, "xml")
    .fail(function(jqxhr, textStatus, errorThrown) {
      console.log(errorThrown)
    });