I feel foolish for asking something so trivial, but I really want the best-practices answer (I'm not looking for a "setTimeout" solution unless nothing else is possible -- though I doubt that is the case).
The quick over-view: I have an array which I want to push to from within a callback. After I've populated the array I then want to use it, outside of the callbacks.
The practical use: I have an array of cities, I want to geocode them with Google's API and populate an array with all of the resulting LatLng's. Later I will create marker objects with them, add them to a clusterer, whatever.
coder = new google.maps.Geocoder();
$places = ['Truro, NS', 'Halifax, NS', 'Sydney, NS', 'Dartmouth, NS'];
all_the_pins = Array();
for(i in $places){
var $place = $places[i];
coder.geocode({address:$place}, function(res, stat){
switch(stat){
case 'OK':
all_the_pins.push(res[0].geometry.location);
break;
}
});
}
console.log(all_the_pins);
EDIT: to clarify the issue:
The problem isn't a question of scope or whether or not the all_the_pins
variable is global or not, if you were to examine all_the_pins
within the callback you will see that it is the same variable (which is being pushed to). The problem is that because the pushes happen within the callback they don't happen before the console.log
is run below.