Chaining promises and promise handlers
Much of the purpose of promises is to allow the developer to serialize and reason about independent asynchronous actions. This can be accomplished by utilizing promise chaining in AngularJS.
Getting ready
Assume that all the examples in this recipe have been set up in the following manner:
var deferred = $q.defer() , promise = deferred.promise;
Also, assume that $q
and other built-in AngularJS services have already been injected into the current lexical scope.
How to do it…
The promise handler definition method then()
returns another promise, which can further have handlers defined upon it in a chain handler, as shown here:
var successHandler = function() { $log.log('called'); }; promise .then(successHandler) .then(successHandler) .then(successHandler); deferred.resolve(); // called // called // called
Data handoff for chained handlers
Chained handlers can pass data to their subsequent handlers, as follows:
var successHandler = function(val) { ...