gpt4 book ai didi

javascript - Angular q 所有动态结果

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:04:30 24 4
gpt4 key购买 nike

我需要等待两个 promise 在做某事之前解决。问题是有时我只能根据客户想要的发送一个 promise ,我需要指望来自这个 $q 的结果。全部。如何动态定义变量?

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

promises 在一个对象中解析,所以它们被命名,而不是有一个数组,你得到一个带有属性的解析对象,所以不要做 arr[0] ,这可能是乱序的,你会做 resolved.hunters 或resolved.drawOrder。该解决方案只是嵌套到 $scope 一级并自动执行。

关于javascript - Angular q 所有动态结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27587481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com