0

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.

P K
  • 3
  • 2

1 Answers1

0

This is because you're $scope.markers = markers; before all the calls have been performed. You need to call $q.all in order to wait for all the promises:

var p = gf.get(key).then(function(location) { 
    return ({
      idKey: key,
      title: post.title,
      coords: {
        latitude: location[0],
        longitude: location[1]
      }
     });
});
markers.push(p);

And then, wait for all the requests and perform your addition:

$q.all(markers).then(function(markers) {
     $scope.markers = markers;
});

You can use Array.prototype.map to save the "create empty array and then add" part.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Thanks! I've tried the code, but I'm still getting the same problem. If I console.log(post.title) after "var p = gf.get(key).then(function(location) { ", I still getting repeating data. – P K Mar 11 '16 at 22:00
  • Thanks for the help! I've read your answer, but I'm still having trouble figuring it out. Te get(key) function returns a promise. My understanding is that "get" should finish before .then runs. Therefore, I shouldn't have any problems with the repeating data. – P K Mar 17 '16 at 13:26