I\'m trying to get a handle on the Angular $q
service and its related objects and APIs. When I look at the objects in my console I see:
var defe
1) $q.reject()
is a shortcut to create a deferred and then reject it immediately; I often use this in an errorFn if I can't handle the error.
2) Nothing, promise.catch(errorFn)
is just syntactic sugar for promise.then(null, errorFn)
, just like the success and error methods of the $http
service, so you can write code like the following:
promise.
then(function(result){
// handle success
return result;
}, function errorHandler1(error){
// handle error, exactly as if this was a separate catch in the chain.
}).catch(function errorHandler2(error){
// handle errors from errorHandler1
});
3) This is exactly where $q.reject can come in handy:
promise.
catch(function(error){
//Decide you can't handle the error
return $q.reject(error); //This forwards the error to the next error handler;
}).catch(function(error){
// Here you may handle the error or reject it again.
return 'An error occurred';
//Now other errorFn in the promise chain won't be called,
// but the successFn calls will.
}).catch(function(error){
// This will never be called because the previous catch handles all errors.
}).then(function(result){
//This will always be called with either the result of promise if it was successful, or
//'An error occured' if it wasn't
});