Skip to content Skip to sidebar Skip to footer

$q.reject And Handling Errors In Angularjs Chained Promises

I'm having trouble understanding a basic concept of error handling with chaining promises. In order to learn the rules, I have written a simple example, guessing what the result wi

Solution 1:

Your understanding is correct, and the problem appears to lie somewhere in the way you are trying to observe this behavior (in something you haven't shown us).

If you return a rejected promise from either a success or error handler in then(), then the promise returned by then() will resolve to a 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 a value:', value);
        return $q.reject('Error!');
    });

    var promise2 = promise1.then(function (data1) {
        return"Got some stuff";
    }, function (error) {
        console.log("Caught an error:", error);
        return $q.reject('New error');
    });

    var promiseend = promise2.then(function (data2) {
        return data2;
    }, function (error) {
        console.log('Caught an error:', error);  // <-- this is logged to the consolereturn error;
    });

    return promiseend;
}]);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script><divng-app='app'ng-controller='C'></div>

One thing to note here is that in that last handler, you are returning the error variable, and not throwing an exception or returning a rejected promise. So in this case, promiseend will successfully resolve with the value of that error variable.

Post a Comment for "$q.reject And Handling Errors In Angularjs Chained Promises"