Chain promises with AngularJS

后端 未结 2 1800
生来不讨喜
生来不讨喜 2020-12-05 17:49

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

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


        
相关标签:
2条回答
  • 2020-12-05 18:29

    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;
    }
    
    0 讨论(0)
  • 2020-12-05 18:36

    Make all methods atomar, by adding their own promises. In your code, the first resolve will complete the whole request.

    If the methods have their own promise, you can chain them with ease.

    angular.module('deps-app.payment.services', []).factory('paymentStrategy', function($q) {
    var ITEM_TO_PURCHASE = "test.beer.managed";
    
    _init = function() {
      return $q(function (resolve, reject) {
        inappbilling.init(resolve, reject, { showLog: true }); 
      });
    };
    
    _purchase = function() {
      return $q(function (resolve, reject) {
        inappbilling.buy(resolve, reject, ITEM_TO_PURCHASE);  
      });
    };
    
    _consume = function() {
      return $q(function (resolve, reject) {
        inappbilling.consumePurchase(resolve, reject, ITEM_TO_PURCHASE);
      });
    };
    
    return  {
      // In this case, you don't need to define a additional promise, 
      // because placing a return in front of the _init, will already return 
      // the promise of _consume.
      buy: function() {    
        return _init()
          .then(_purchase)  
          // remove () from inside the callback, to pass the actual method 
          // instead the result of the invoked method.
          .then(_consume);      
      }    
    };
    

    });

    0 讨论(0)
提交回复
热议问题