AngularJS 的链式承诺 [英] Chain promises with AngularJS
问题描述
我有一个名为 paymentStrategy 的服务,它被注入到我的控制器中.
I have a service called paymentStrategy that get injected in my controller.
$scope.buy = function() {
paymentStrategy.buy()
.then(function(response) {
}
}
这个来自 paymentStrategy 的购买方法触发了几个需要顺序调用的方法.当buy()中的所有方法都完成后,需要调用then().
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.
这可能是微不足道的,但我对 angular 很陌生.
It is probably trivial but I am quite new to angular.
目前,buy().then() 在 init() 方法之后被直接触发.我觉得我们需要将所有这些方法放在一个 promise 数组中并应用 $q.all().
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;
}
}
});
推荐答案
通过添加自己的承诺,使所有方法原子化.在您的代码中,第一个 resolve
将完成整个请求.
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);
}
};
});
这篇关于AngularJS 的链式承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!