【发布时间】:2014-11-16 11:28:46
【问题描述】:
我有一个对服务器的 $http 调用链。如果一个呼叫失败,我想向用户显示通知并停止链。起初我以为我可以使用 $q.reject 来停止链,但事实证明程序流程继续到下一个then 的错误处理程序。我也尝试过不返回任何内容,但流程仍在继续。
我可以停止流中链吗?所以例如下面的脚本应该打印result: |A|D|F而不是result: |A|D|F|E|H|J。
如果无法在链中停止流,我必须在每个then 的错误处理程序中添加额外的条件,还是有更优雅的方式?
angular.module("MyModule", []).controller("MyCtrl", ["$scope", "$q", "$timeout",
function($scope, $q, $timeout) {
$scope.result = "";
var d0 = $q.defer();
$timeout(function() {
d0.reject("A"); // the promise will fail
}, 1000);
d0.promise.then(
function(response) {
$scope.result += "|" + response + "|B";
var d1 = $q.defer();
$timeout(function() {
d1.resolve("C");
}, 1000);
return d1.promise;
},
function(response) {
$scope.result += "|" + response + "|D";
return $q.reject("E");
}
).finally( // it should stop here ...
function() { $scope.result += "|F"; }
).then(
function(response) {
$scope.result += "|" + response + "|G";
},
function(response) { // ... but instead it continues here
$scope.result += "|" + response + "|H";
return $q.reject("I");
}
).finally(
function() { $scope.result += "|J"; }
)
}
]);
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="MyModule" ng-controller="MyCtrl">
result: {{result}}
</div>
【问题讨论】: