I am trying to loop through an array of objects(posts). Within the loop is a query to a geofire database (gf.get()). It retrieves the gps location of a certain key. The data is then pushed to an array.
var posts = PostsData.getPosts();
$scope.$watch($scope.active, function() {
$timeout(function() {
var markers = [];
for (var key in posts) {
var post = posts[key];
if (posts.hasOwnProperty(key) && posts[key]!=null) {
gf.get(key).then(function(location) {
console.log(post.title);
console.log(key);
markers.push({
idKey: key,
title: post.title,
coords: {
latitude: location[0],
longitude: location[1]
}
})
})
$scope.markers = markers;
}
}
})
})
The output from the following code....
console.log(post.title);
console.log(key);
is the same key and title over and over again, which is not representative of the data ins "posts" (the key and titles are unique).
I believe my problem is due to a poor understanding of asynchronous calling, promises, etc.
Any help would be much appreciated.