Angular.js Promises – Deferred and Promise handling

A promise is an object that represents the return value or the thrown exception that the function may eventually provide. A promise can also be used as a proxy for a remote object to overcome latency.

Promises are highly useful when you wish to synchronize multiple asynchronous functions and also want to avoid Javascript callback hell. as following is a asynchronous example.

step1(function (value1) {
 step2(value1, function(value2) {
 step3(value2, function(value3) {
 // do something.
 });
 });
});

and alternative use of promise library for above example is:

Q.fcall(promise1)
.then(promise2)
.then(promise3) {
 // Do something
})
.catch(function (error) {
 // Handle any error from all above steps
})
.done();

Angular.js provide a service $q with implementation of promises/deferred objects inspired by Kris Kowal’s Q.  you can simply start using it as a service.

angular.module('PromiseExample').controller('PromiseCtrl', ['$scope', $http, $q, function ($scope, $http, $q) {
 
 function getUser(){
   var deferred = $q.defer();
   $http.get(ApiUrl+ '/user/' + $scope.uuid)
   .success(function(result){
    deferred.resolve(result);
   })
   .error(function(error){
     deferred.reject(error);
   });
 
   return deferred.promise;
 }

 getUser().then(function(user){
   $scope.user = user;
 });

}]);

In above code, getUser() is creating a $q.defer() object which has returned a promise at the end of function, we have called it remote object earlier above. now deffered.resolve provide us the results in case of success and deffered.reject object gonna tell us the reason why it failed.

$q.defer() also have a method notify() which gives the status of the promise’s execution. This may be called multiple times before the promise is either resolved or rejected.

You can also wrap multiple promises using $q.all. all function combines multiple promises into a single promise and later on you can foreach through responses.

var first = $http.get("/api/v1/user/educations/"+user_id),
second = $http.get("/api/v1/user/employments/"+user_id),
third = $http.get("/api/v1/user/posts/"+user_id);

$q.all([first, second, third]).then(function(result) {
// foearch through all responses.
angular.forEach(result, function(response) {
console.log(response.data);
});
});

If you want to take look at further examples of Promises, you can see it Kris Kowal’s Q and Angular $q service