我希望通过 Firebase 事务增加几个计数器,并在 firebase 中添加一个新值。关键是我想确保它全部成功或不保存任何数据。
我想这最好通过 promise 来完成?不幸的是我对他们不是很熟悉
到目前为止,我有:
$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
最佳答案
您可能需要查看 $q.all作为 promise 的包装。本质上,如果所有 promise 都成功了,那么当 promise 列表得到满足时,$q.all promise 就会被解决,否则就会被拒绝。
//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
}
)
关于angularjs - 您如何/如何在 for 循环内链接 firebase 事务的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20848684/