在做某事之前,我需要等待两个承诺才能解决.问题是,有时我只能根据客户的需要发送一个承诺,我需要依靠来自这个$q.all的结果.如何动态定义变量?
var makePurchasetoResolve = [];
if( CartService.items.draws.length ) {
var drawOrder = {};
drawOrder.price = $scope.getTotal();
drawOrder.paymentMethodId = $scope.payment.paymetMethodId;
drawOrder.orderItems = CartService.items.draws;
drawOrder.payFromBalance = false;
makePurchasetoResolve.push(DrawService.makePurchase(drawOrder));
}
if( CartService.items.hunters.length ) {
var hunterOrder = {};
hunterOrder.paymentMethodId = $scope.payment.paymetMethodId;
hunterOrder.orderItems = CartService.items.hunters;
makePurchasetoResolve.push(HunterService.makePurchase(hunterOrder));
}
$q.all(makePurchasetoResolve).then(function( res ) {
$q.all([HunterService.getPurchase(res[0].data.data),DrawService.getPurchase(res.data.data)]).then(function() {
//here is the problem, because i dont kNow if i have the two promises to resolve or only one
$scope.hunters = res[0].data.data[0];
$scope.drawOrder = res[1].data.data;
})
}
解决方法:
一个鲜为人知的事实是$q.all也可以采用一个对象而不是一个可以简化你的生活的数组:
var purchases = {}; // an object rather than an array for named properties
if( CartService.items.draws.length ) {
//...
purchases.drawOrder = DrawService.makePurchase(drawOrder); // named assign
}
if( CartService.items.hunters.length ) {
//...
purchases.hunters = HunterService.makePurchase(hunterOrder);
}
// any more additions to the objects here..
$q.all(purchases).then(function(resolved){
// resolve anything further you need
$scope.purchases = resolved; // Add $scope.purchases.hunters etc
});
承诺在一个对象中解析,因此它们被命名,而不是一个数组,你得到一个具有属性的已解析对象,而不是做arr [0],这可能是乱序,你可以解决.hunters或resolved.drawOrder .这个解决方案只是嵌入$scope范围内并自动完成.