如何/可以在for循环中链接firebase事务的promises

时间:2013-12-30 22:34:13

标签: angularjs firebase promise angularfire

我希望使用Firebase事务增加几个计数器,并在firebase中添加一个新值。关键是我要确保它是否全部成功保存任何数据。

我想这最好用承诺来完成?不幸的是我对它们不是很熟悉

到目前为止,我有:

$scope.addNewPost = function() {
  var ref = new Firebase(FBURL).child('/posts').push();
  var onComplete = function(error) {
    if (error) {
      alert('Error: Something went wrong when creating your post please try again');
      throw new Error(error);
    } else {
      $scope.reset(); // or redirect to post
    }
  };
  var tags = $scope.post.tags.split(', ');
  console.log(tags);
  angular.forEach(tags, function(value, index){
    var refTag = new Firebase(FBURL).child('/tags/' + value);
    refTag.transaction(function(current_value) {
      return current_value + 1;
    });
  });
  ref.set($scope.post, onComplete);
};

有人能指出我如何实现这一目标或提供建议吗? 也许有更好的Angularfire方法来做到这一点?

将跟进问题移至new question dealing specifically with error handling

1 个答案:

答案 0 :(得分:3)

您可能希望将$q.all视为承诺的包装。基本上,如果所有承诺都成功完成承诺列表,则会解决$ q.all承诺,否则将被拒绝。

//assuming $q is injected as a service
var transactions = [];
angular.forEach(tags, function(value, index){
  var dfd = $q.defer();
  var refTag = new Firebase(FBURL).child('/tags/' + value);
  refTag.transaction(function(current_value) {
    dfd.resolve( current_value + 1 );
    return current_value + 1;
  });
  transactions.push( dfd.promise );
});

$q.all( transactions ).then(
  function(){ 
    /*Resolved values of the promises are set to arguments in order*/
    ref.set( $scope.post, onComplete ); 
  },
  function(){
   //generally handle errors here, but your example does not show rejections are possible
  }
)