Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  190] [ 2]  / answers: 1 / hits: 39255  / 11 Years ago, thu, september 12, 2013, 12:00:00

I need to create chained promises:



var deferred = $q.defer();
$timeout(function() {
deferred.reject({result: 'errror'});
}, 3000);
deferred.promise.then(angular.noop, function errorHandler(result) {
//some actions
return result;
}).then(function successCallback(result) {
console.log('what do I do here?');
return result;
}, function errorCallback(result) {
$scope.result= result;
return result;
});


If I put an errorCallback into the first then, the second then will be resolved and its successCallback will be called . But if I remove errorHandler then second promise will be rejected.



According to Angular JS docs the only way to propagate rejection is to return $q.reject(); and it looks not obvious, especially because I have to inject $q service even if it is not needed;



It can also be done by throwing an exception in errorHandler, but it writes exception trace to console, it is not good.



Is there another option to do this in a clear way? And what is the reason? Why it is done? In which case, the current behavior can be useful?


More From » angularjs

 Answers
14

And what the reason why it is done. In which case, the current behavior can be useful?




It can be useful when in errorHandler you could try to repair error state and resolve promise somehow.



var retriesCount = 0;

function doWork()
{
return $http.post('url')
.then(function(response){
// check success-property of returned data
if(response.data.success)
// just unwrap data from response, may be do some other manipulations
return response.data;
else
// reject with error
return $q.reject('some error occured');
})
.catch(function(reason){
if(retriesCount++ < 3)
// some error, let me try to recover myself once again
return doWork();
else
// mission failed... finally reject
return $q.reject(reason);
});
}


doWork().then(console.log, console.error);

[#75741] Wednesday, September 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckaylab

Total Points: 311
Total Questions: 120
Total Answers: 93

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
;