在下面的代码片段中,错误1和成功2将被记录。如果原始延迟被拒绝,我如何可以传播被调用的错误回调,而不是正在调用的成功回调。
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>
通过在错误回调中返回$ q.reject来传播错误
var deferred = $q.defer(); deferred.reject(); deferred.promise .then( /*success*/function () { console.log("success 1"); },/*error*/function () { console.log("error 1"); return $q.reject('error 1')}) .then( /*success*/function () { console.log("success 2"); },/*error*/function () { console.log("error 2"); }); });