Praveen Prasad
Praveen Prasad

Reputation: 1993

How can I write a promise in AngularJS

I am trying to write a service, which does multiple async requests, I am using $q to return a promise, problem is I am writing some repetitive code, I want to remove the repetition.

app.factory('MyService',function($q){
     var ser = {
            getA:function(){                
                var d=  $q.defer; //repetitive code
                asyn1().then(function(){
                    aync2().then(function(res){
                        //Process data
                        doSomething(res)
                        d.resolve();
                    })
                });
                return d.promise
            } ,
            getB:function(){
                var d=  $q.defer;
                asyn3().then(function(){
                    aync4().then(function(res){
                        //Process data
                        doSomething(res)
                        d.resolve();
                    })
                });
                return d.promise
            }                            
     }

     return ser;
});

In each function, I am repeating the $q thing, how can I avoid the repetition.

Upvotes: 2

Views: 971

Answers (3)

Mickael Vikoroff
Mickael Vikoroff

Reputation: 1

Demo on my jsFiddle page: https://jsfiddle.net/MikaViko/kprbneha/

``var module = angular.module('app', []);
    module.controller('appController', ['$scope', '$q', function($scope, $q) {

      var fibonacci = [1, 1, 2, 3, 5, 8, 13, 20];

      $scope.getItem = function(index) {
        var promise = getItemPromise(index);
        promise.then(
          function(item) {
            $scope.item = item;
            $scope.error = "";
          },
          function(error) {
            $scope.error = error;
            $scope.item = null;
          }
        );
      };

      function getItemPromise(index) {
        var item = fibonacci[index];
        var deferred = $q.defer();

        if (item)
          deferred.resolve(item);
        else
          deferred.reject("L'item n'existe pas ou l'index n'est pas valide.");

        return deferred.promise;
      }

    }]);

Upvotes: 0

vbuhlev
vbuhlev

Reputation: 509

The idea of promises is to write code which doesn't increase the indentation to the right and also deals with a thing called 'callback hell'.

This code

          getA:function(){                
            var d=  $q.defer; //repetitive code
            asyn1().then(function(){
                aync2().then(function(){
                    d.resolve();
                })
            });
            return d.promise
        }

can be rewritten like that

          getA:function(){
            return async1()
              .then(async2)
              .then(processTheResultOfAsync2);
          }

or if you need to some synchronous processing of the result from async1

          getA:function(){
            return async1()
              .then(function(result) {
                 ..... soome synchronous processing
                 return async2(processed);
              });
          }

or if you need async processinc

        getA:function(){
            return async1()
              .then(function(result) {
                 return processAsync(result)
                   .then(async2);
              });
          }

Promises should make your life simpler and if this is not happening you are not using them right!

https://github.com/kriskowal/q

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691715

Use promise chaining:

getA: function() {                
    return asyn1().then(function(responseFromAsyn1) {
        return aync2(responseFromAsyn1);
    }).then(function(responseFromAsync2) {
        return postProcess(responseFromAsync2);
    });
}

getA() is now much shorter than your original code, and also more correct: the caller will actually get a rejected promise if asyn1() or async2() fails.

Upvotes: 3

Related Questions