I have a chain of $http calls to server. If one call fails I want to display notification to user and stop the chain. At first I thought I can use the $q.reject to stop the chain, but it turned out the program flow continues to the next then
's error handler. I have also tried returning nothing, but the flow still continues.
Can I stop the flow mid chain? So for example the script below should print result: |A|D|F
instead of result: |A|D|F|E|H|J
.
If the flow cannot be stopped mid chain, must I add extra condition in each then
's error handler, or is there more elegant way?
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>