$q.reject and handling errors in AngularJS chained promises

别来无恙 提交于 2019-11-30 20:26:35

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 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 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!