简体   繁体   中英

Can only one error / success function be assigned for AngularJS $http promises?

I'm trying to do the following:

$http.get('..').error(someFunc).error(someFunc2);

However it doesn't appear to be working, I get various errors.

I thought it was possible to chain multiple methods in this way? What am I doing wrong?

If you do :

$http.get('..').error(someFunc).error(someFunc2);

someFunc2 will only fire if someFunc throws an error. This is in line with the code snippet that Jonathan Lonowski pointed out : https://github.com/angular/angular.js/blob/v1.1.5/src/ng/http.js#L714-L719

If you want to run multiple functions you can do:

$http.get('..').error(function () {someFunc();someFunc2();});

More elegant way using promise chaining . For error only handling:

$q.all($http.get('..')).catch(function(errorReason) {...}).catch(function(errorReason) {...})

For success/error handling:

$q.all($http.get('..')).then(function(response) {...}, function(errorReason) {...}).then(function(response) {...}, function(errorReason) {...})

However it doesn't appear to be working

Yes, it does work. But notice that the error method works so that your snippet is equivalent to

var promise = $http.get('..');
promise.error(someFunc);
promise.error(someFunc2);

If you expected chaining behaviour, where someFunc2 catches only the errors thrown in someFunc , use the .catch() method instead of .error() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM