How/can do you chain promises for firebase transac

2019-05-04 18:45发布

问题:

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

So far I have:

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

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?

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

回答1:

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