[英]How do I execute a function after all resources have resolved?
How do I delay execution of a function until after all of my $resources
have resolved? 在所有
$resources
解决之后 ,如何延迟执行函数? My goal here is to be able to parse though the log
array after all $resources
have resolved and push a single success notification to the UI instead of pushing one notification per each success. 我的目标是在所有
$resources
解决之后,能够解析log
数组,并将单个成功通知推送到UI,而不是每次成功推送一个通知。
I've based my code below off of this question angular -- accessing data of multiple http calls - how to resolve the promises . 我基于以下角度解决了我的代码-访问多个http调用的数据-如何解决承诺 。 I realize that
$scope.promises
is empty because item.$save()
doesn't return anything but I hope you can see that I'm trying to push the unresolved promise to the promises
array. 我意识到
$scope.promises
为空,因为item.$save()
不返回任何内容,但我希望您能看到我正在尝试将未解决的promise推入promises
数组。
$scope.save = function () {
$scope.promises = [];
$scope.log = [];
angular.forEach($scope.menuItems, function(item) {
$scope.promises.push(item.$save(function(menu){
debugger; // execution gets here 2nd
console.debug("success");
$scope.log.push(msg: 'success');
}));
}, this);
$q.all($scope.promises).then(function() {
debugger; // execution gets here 1st
console.debug("all promises resolved");
});
};
Since $save
does not return a promise, you will need an intermediate one: 由于
$save
不返回承诺,因此您将需要一个中间的承诺:
angular.forEach($scope.menuItems, function(item) {
var d = $q.defer(); // <--- the intermediate promise
item.$save(
function(menu){
debugger;
console.debug("success");
$scope.log.push(msg: 'success');
d.resolve(menu); // <--- resolving it, optionally with the value
},
function(error){
d.reject(error); // <--- rejecting it on error
}
);
$scope.promises.push(d.promise);
}, this);
By the way, do not forget to throw away the array of promises, or you will keep garbage: 顺便说一句,不要忘了丢弃承诺数组,否则您将保持垃圾状态:
$q.all($scope.promises).then(...).always(function() {
$scope.promises = null;
});
And, if $scope.promises
is NOT exposed to the view, it does not need to be in the scope; 而且,如果
$scope.promises
不容易看到,它并不需要在范围; it can be just a var. 它可以只是一个变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.