一尘不染

链承诺与AngularJS

angularjs

我有一个名为PaymentStrategy的服务,已注入我的控制器中。

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

  }
}

paymentStrategy中的这种购买方法会触发几种需要顺序调用的方法。当buy()中的所有方法都完成后,需要调用then()。

这可能是微不足道的,但我对棱角还很陌生。

目前,在init()方法之后立即触发buy()。then()。我觉得我们需要将所有这些方法放在一个promise中,并应用$ q.all()。

任何帮助或建议,将不胜感激

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;                    
    }

 }
});

阅读 210

收藏
2020-07-04

共1个答案

一尘不染

通过添加自己的承诺使所有方法变得原子化。在您的代码中,第一个resolve将完成整个请求。

如果这些方法有自己的承诺,则可以轻松地将它们链接起来。

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);      
  }    
};

});

2020-07-04