使用geofire和firebase迭代对象数组

时间:2016-03-11 17:08:38

标签: angularjs firebase promise q geofire

我正在尝试遍历一组对象(帖子)。 循环内是对地理数据库(gf.get())的查询。它检索某个键的gps位置。然后将数据推送到数组。

  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;
     }
  }
})

})

以下代码的输出....

        console.log(post.title);
        console.log(key);

一遍又一遍地使用相同的密钥和标题,这不代表ins“posts”中的数据(密钥和标题是唯一的)。

我认为我的问题是由于对异步调用,承诺等的理解不足而导致的。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

这是因为您在执行所有通话之前已经$scope.markers = markers;了。您需要致电$q.all以等待所有承诺:

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

然后,等待所有请求并执行添加:

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

您可以使用Array.prototype.map保存"创建空数组,然后添加"部分。

相关问题