Promise in Angular

Async programming is very populer in programming community especially for back-end developers but not as much as  front-end developers (client side programming) . Javascript is growing very fast and async programing is a must for front-end developers now.

Javascript have some technic to use async programming. First one is a callback functions but if you have more then 3 functions working async ,callback functions starting to be hard to manage.

At this point promise helps us a build async functions with clean and readable code. There are some promise algorithms such as  Q or Bluebird. Angular using Q promise with $q service and today we will look how $q works in Angular.

As a first step we have to add $q as a dependency in angularjs dependency injection container like below.

.factory('productService', function($http, $log, $q) {

Now we are able to use $q service, $q has 3 main functions and they are defer , resolve  and  reject . Deffered is starting promise code block, if function runs successfully deferred.resolve() will work and if will be a problem deferred.rejected() will run and say the listener of function there is a problem about function.

You can check below sample factory usign $q promise logic.

.factory('productService', function($http, $log, $q) {
  return {
   getProduct: function(parameter) {
     var deferred = $q.defer();
     $http.get('/api/method/' + parameter)
       .success(function(data) { 
             title: data.title,
             cost: data.price});
       }).error(function(msg, code) {
          $log.error(msg, code);
     return deferred.promise;

I hope tutorial will help you. If you are any question fell free to write me.



Leave a Reply

Your email address will not be published. Required fields are marked *