In the following code snippet error 1
and success 2
will be logged. How can I can I propagate error callbacks being invoked rather than the success callbacks being invoked if the original deferred is rejected.
angular.module("Foo", []);
angular
.module("Foo")
.controller("Bar", function ($q) {
var deferred = $q.defer();
deferred.reject();
deferred.promise
.then(
/*success*/function () { console.log("success 1"); },
/*error*/function () { console.log("error 1"); })
.then(
/*success*/function () { console.log("success 2"); },
/*error*/function () { console.log("error 2"); });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="Foo">
<div ng-controller="Bar"></div>
</div>
.catch()
instead of.then(onSuccess, onFailure)
– Senegal"catch": function(callback) { return this.then(null, callback); }
. – Unaccountablethen
, it would propagate down to thecatch
. You implicitly reject without using$q.reject
simply by not handling it – Senegalthen(angular.noop, angular.noop)
is different than callingthen(angular.noop, null)
because angular will assume you did not try to correct the error if you don't pass in an error callback, so it will propagate the rejection by presumably calling$q.reject
(or something analgous) under the hood. However, it will assume you tried to correct the error if you provide an error callback. To not confuse other readers, we should point out this has nothing to do with.catch
. – Unaccountablecatch
is only shortcut for.then(null, fn)
. I find more readable too -- to leavethen
only for successes and placecatch
as needed to get as finegrained control as you want, doing things like instanceOf on the errors and handling or rethrowing etc as you need to (reject
insidethen
appears odd to me). – Senegal.then(angular.noop, angular.noop).catch(function () { console.log("caught"); }
vs.then(angular.noop, null).catch(function () { console.log("caught"); }
. You'll find the log statement is never printed in the first code snippet. Note, the second code snippet is equivalent to.then(angular.noop).catch(function () { console.log("caught"); })
. – Unaccountable.then(function () { /*do stuff*/}).catch(function () { console.log("caught"); })
is equivalent to.then(function () { /*do stuff*/}).then(null, function () { /*handle errors*/ })
and arguably more useful than.then(function {/*do stuff*/}, function () { /*handle errors*/})
because you can handle the errors from your success callback. – Unaccountable