问题
So I have a simple example of using $q.all to batch $resource calls, what I want to know is why is my update handler never called?
I would have thought it would be called after each promise is successfully completed?
Only the result handler is called. What am I doing wrong?
Here is the code snippet:
var promises = [];
angular.forEach($scope.mappedData, function(item) {
var resource = new Resource(item);
promises.push(resource.$save());
});
$q.all(promises).then(
function(result) {
console.log('result', result);
},
function(error) {
console.log('error', error);
},
function(notify) {
console.log('notify', notify);
}
);
回答1:
$q.all creates a new singular promise that once all the previous promises are complete will then continue on. If you want to do each one individually you'll have to reference them individually.
回答2:
I had the same problem, and I came with this solution. I've tried to arrange the code for your case.
var results = [], errors = [], d = $q.defer()
angular.forEach($scope.mappedData, function(item) {
var resource = new Resource(item);
resource.$save().promise
.then(function (result) {
results.push(result)
if(results.length == $scope.mappedData.length)
d.resolve(results)
}, function (err) {
errors.push(err)
results.push(null) // Very important =P
}, function (notf) {
d.notify(notf)
})
})
d.promise.then(function (results) {
console.log(results)
}, function (err) {
console.error(err)
}, function (notf) {
console.info(notf)
})
Let me know if it helps ;)
来源:https://stackoverflow.com/questions/28322912/angularjs-q-all-update-notify-not-called-why