0

I have a global array in my script that obtains its values from a specific function call. See the example:

var myglobalArray = []; 
.
.
.

function createMarkersToFillArray(property1, property2) {
    var marker= new google.maps.Marker({ position: latlng, map: map });
    marker.property1 = property1;
    marker.property2 = property2; 
    myGlobalArray.push(marker);
    return marker;
}

function getStuffFromXMl() {
    downloadUrl("myXMLFile.xml", function (data) {      
             var xmlItems = data.documentElement.getElementsByTagName("row");

             for (var i = 0; i < xmlItems.length; i++) {

                 var property1= xmlItems[i].getAttribute("Property");
                 var property2 = xmlItems[i].getAttribute("Property2");
                 var marker = createMarkersToFillArray(property1, property2);
             }
   });
}

The code above is doing exactly what I expected it to do. The problem occurs when I try to access myGlobalArray's elements inside the initialize() function.

function initialize() {
    getStuffFromXML(); //this should populate myGlobalArray with the markers, but it doesn't
}

It says that the array is empty, even though the markers are being added into the array. Could someone explain why myGlobalArray's elements appear to vanish when I try to access them inside the initialize() function?

ic3man7019
  • 721
  • 6
  • 24
  • 2
    through my crystal ball: `downloadUrl` is asynchronous – Igor Jan 29 '16 at 15:06
  • I'm not concerned with the async part; like I said, that part is working. I want to know why the values of the `myGlobalArray` can be accessed in the `getStuffFromXML()` function and the `createMarkersToFillArray()` function, but not the `initialize()` function. – ic3man7019 Jan 29 '16 at 15:10
  • 1
    "I'm not concerned with the async part" - you should be. Function `initialize` finishes way before `downloadUrl` callback is executed. – Igor Jan 29 '16 at 15:13
  • 1
    Because it's ***asynchronous***. You're trying the access the values in `initialize` *before* they exist. Asynchronicity should very much concern you. – deceze Jan 29 '16 at 15:13
  • So, even though the initialize function calls the getStuffFromXML function in the very first line, the values still are not there before the initialize function tries to access them? – ic3man7019 Jan 29 '16 at 15:16
  • Because `downloadUrl()` finishes ***asynchronously*** in the background *sometime later*. That's what that means. – deceze Jan 29 '16 at 15:36
  • Well, despite your condescending tone and unnecessary remarks, I appreciate the help. I'll figure it out. – ic3man7019 Jan 29 '16 at 15:56

0 Answers0