您如何/如何在 for 循环内链接 firebase 事务的承诺 [英] How/can do you chain promises for firebase transactions inside a for loop

查看:25
本文介绍了您如何/如何在 for 循环内链接 firebase 事务的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望通过 Firebase 事务增加几个计数器,并在 firebase 中添加一个新值.关键是我想确保它全部成功或不保存任何数据.

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?

将后续问题移至 专门处理错误处理的新问题

推荐答案

您可能需要查看 $q.all 作为 Promise 的包装器.本质上,当一个承诺列表都得到满足时,如果所有承诺都成功,$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
  }
)

这篇关于您如何/如何在 for 循环内链接 firebase 事务的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆