Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a service called paymentStrategy that get injected in my controller.

$scope.buy = function() {
  paymentStrategy.buy()
    .then(function(response) {

  }
}

This buy method from paymentStrategy triggers several methods that needs to be called sequentially. When all the methods within buy() are done, then() needs to be called.

It is probably trivial but I am quite new to angular.

At the moment, buy().then() gets triggered straight after the init() methods. I have the feeling we need to put all theses methods in a array of promises and apply $q.all().

Any help or suggestion would be greatly appreciated

angular.module('deps-app.payment.services', []).
  factory('paymentStrategy', function($q) {

 var deferred = $q.defer();
 var ITEM_TO_PURCHASE = "test.beer.managed";
 var promises = [];

 var handlerSuccess = function(result) {
      deferred.resolve(result);
  };

 var handlerError = function(result) {
      deferred.reject(result);
  };

 _init = function() {

     inappbilling.init(handlerSuccess, handlerError, { showLog:true }); 
     return deferred.promise;
    }

  _purchase = function() {
        inappbilling.buy(handlerSuccess, handlerError, ITEM_TO_PURCHASE);
        return deferred.promise;
  }

  _consume = function() {
        inappbilling.consumePurchase(handlerSuccess, handlerError, ITEM_TO_PURCHASE);
        return deferred.promise;
  }

return  {

     buy: function() {

      _init();
        .then(_purchase());
        .then(_consume());  

      return deferred.promise;                    
    }

 }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
360 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you need to chain promises in Angular sequentially, you can simply return the promises from one to another:

callFirst()
.then(function(firstResult){
   return callSecond();
})
.then(function(secondResult){
   return callThird();
})
.then(function(thirdResult){
   //Finally do something with promise, or even return this
});

And if you want to return all of this as an API:

function myMethod(){
   //Return the promise of the entire chain
   return first()
           .then(function(){
               return second();
           }).promise;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...