I am getting some weird behaviour with the following, it shows an array length of 0 eventhough printing it right before that shows that there clearly is a length greater tha
So what actually happens is that when you log your response it actually having length as 0. But after the asynchronous response is returned it has 42 items but length being a property is logged as number. But your response being an object is logged initially with zero items. But when the actual response is received the reference to the response object is updated and you see that the response is having 42 items and length is also 42. The below code is an example for that that to show after the setTimeout
is called the logged response is updated in the console.
var getTopSelection = function(callback) {
var topSelection = [];
markers=[1,2,3,4,5,6,7,8,9];
for(var i=0; i < markers.length; i++) {
if(markers[i].map !== null) {
var stationID = markers[i].id;
getTrips(stationID, function(response) {
topSelection.push({
StationID: i,
Trips: response
});
}, function(error) {
console.log(error);
})
}
}
callback(topSelection);
};
function getTrips(station,fun){
setTimeout(function(){
fun(["trip1","trip2","trip3"]);
},1000)
}
getTopSelection(function(response) {
console.log(response); //115
console.log(response.length); //116
})
Try executing this snippet(have modified accordingly to show what actually happens) in a Fiddle here. And observe the output in console as in stackoverflow snippet result it wont be visible. Here is snap of the Console Output
Hope it helps :)