AngularJS Promise : chain example
A simple example where promises are chained and called one after another. Shows how a rejected promise will break the chain and skip all the next promises until it meets an errorCallback.
HTML
<div ng-app>
<div ng-controller="PromiseCtrl">
{{result}} ({{promises}}) - {{g}}
</div>
</div>
JavaScript
function PromiseCtrl($scope, $q, $timeout) {
// Our promise function with its success condition as argument
var getPromise = function(success) {
// Creates a Deferred object
var deferred = $q.defer();
for(var x = 0; x < 1000; x++) {
var e = x;
}
$scope.g = e;
$timeout(function() {
// Number of promises actually called
++$scope.promises;
// Resolve or reject the promise depending the argument
if(success) {
deferred.resolve("Success");
} else {
deferred.reject("Fail");
}
}, 1000);
// The promise of the deferred task
return deferred.promise;
};
// Init
$scope.result = "Waiting";
$scope.promises = 0;
$scope.g = 0;
$q.when(true).then(function(value) {
return getPromise(true); // Will be resolved (1)
}).then(function(value) {
return getPromise(true); // Will be rejected (2)
}).then(function(value) {
return getPromise(true); // Never called (3)
}).then(function(value) {
$scope.result = value; // Success callback
}, function(value) {
$scope.result = value; // Error callback
});
}