javascript - $q.reject and handling errors in AngularJS chained promises -
i'm having trouble understanding basic concept of error handling chaining promises. in order learn rules, have written simple example, guessing result be. unfortunatly doesn't behave though will. have read multiple articles subject perhaps can't details because of poor english language.
anyway, here code :
var promisestart = $q.when("start"); var promise1 = promisestart.then(function() { return serviceforpromise1.get(); }); var promise2 = promise1.then(function(data1) { return serviceforpromise2.get(data1); },function(error) { return $q.reject(); }); var promiseend = promise2.then(function(data2) { return data2; },function(error) { return error; }); return promiseend;
well know can way better coded it's purpose. here code of serviceforpromise1 function :
function serviceforpromise1() { ... return $http.get(*whatever*).then(function (data){ return data; },function(error) { return $q.reject(); }); }
consider case of serviceforpromise1's failure. $q.reject sent main chain i'm waiting error callback of "promise1 .then(" called , worked expected. decided example transfert error "promise2 .then" in error callback added line return $q.reject(); never reached second error callback (the "promise2 .then" one) , don't understand why (like serviceforpromise1, returned rejected promise !)
i happy understand happening here. help.
your understanding correct, , problem appears lie somewhere in way trying observe behavior (in haven't shown us).
if return rejected promise either success or error handler in then()
, promise returned then()
resolve rejected promise. observe:
angular.module('app', []) .controller('c', [ '$q', function ($q) { var promisestart = $q.when("start"); var promise1 = promisestart.then(function (value) { console.log('got value:', value); return $q.reject('error!'); }); var promise2 = promise1.then(function (data1) { return "got stuff"; }, function (error) { console.log("caught error:", error); return $q.reject('new error'); }); var promiseend = promise2.then(function (data2) { return data2; }, function (error) { console.log('caught error:', error); // <-- logged console return error; }); return promiseend; }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script> <div ng-app='app' ng-controller='c'></div>
one thing note here in last handler, returning error
variable, , not throwing exception or returning rejected promise. in case, promiseend
successfully resolve value of error
variable.
Comments
Post a Comment