如何/可以做你链火力交易承诺内循环火力

2023-09-14 00:26:57 作者:你管我帅不帅又没让你爱

我期待增加几个柜台与火力地堡交易,并添加设置火力点的新值。键为我想,以确保它是所有成功或不保存任何数据。

I am looking to increment several counters with Firebase transactions and also add set a new value in firebase. The key being I want to make sure it is all successful or not save any of the data.

我想这将是最好用的承诺呢?不幸的是我不是很熟悉他们。

I imagine this would be best done with promises? Unfortunately I'm not very familiar with them

到目前为止,我有:

$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的方式来做到这一点?

Could anyone point me towards some references on how I can achieve this or offer advice? Perhaps there is an better Angularfire way to do this?

感动跟进问题成new问题与错误处理专门处理

Moved follow up question into a new question dealing specifically with error handling

推荐答案

您可能要考虑的 $ q.all 作为一个包装周围的承诺。本质上讲,当承诺的清单得到满足,如果所有的人都成功了$ q.all承诺得到解决,否则拒绝。

You may want to look into $q.all as a wrapper around promises. Essentially when a list of promises are fulfilled if all of them were successful the $q.all promise is resolved, otherwise rejected.

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