Creating chained promises is a task I need to tackle:
var deferred = $q.defer();
$timeout(function() {
deferred.reject({result: 'errror'});
}, 3000);
deferred.promise.then(angular.noop, function errorHandler(result) {
//additional actions
return result;
}).then(function successCallback(result) {
console.log('I'm stuck here');
return result;
}, function errorCallback(result) {
$scope.result= result;
return result;
});
Adding an errorCallback in the first then
results in the resolution of the second then
, triggering its successCallback. However, if the errorHandler
is removed, the second promise will be rejected.
As per Angular JS documentation, the sole way to propagate rejection is by returning $q.reject();
. This approach may seem unclear, particularly since the injection of the $q
service is necessary even when unnecessary;
Another option involves throwing an exception within the errorHandler
, but this action logs the exception trace to the console, posing drawbacks.
Is there an alternative method to achieve this clarity? What reasoning stands behind it? Additionally, how can the current behavior prove beneficial in certain scenarios?