AngularJS handling rejected resources in $q.all

2019-04-21 00:24发布

问题:

I'm trying to handle errors with my resources, and then handle rejection of resources in my $q.all().

This is my code:

var user = User.get({id: 1}, function() {
    // Success
}, function(response) {
    // Error
    return $q.reject(response);
});

var promiseList = [user];
$q.all(promiseList).then(function(){
  // Success <-- this seems to run all the time
  }, function(response) {
    // Error <-- this never seems to run but I want it to
});

When my User resource receives a 404, the error callback handles it and returns a $q.reject.

However the success callback in my $q.all gets called, not my error callback. I would've thought because I am rejecting my promise the $q.all error callback would be fired?

I appreciate I only have 1 item in my promiseList but that shouldn't make a difference should it?

回答1:

According to Michael in the comments

I changed

var promiseList = [user];

To this:

var promiseList = [user.$promise];

And now the $q.reject() is being picked up by the $q.all().

Awesome, thanks for the advice.