Angular q所有动态结果

时间:2014-12-21 07:23:21

标签: javascript angularjs 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;          
          })
}

2 个答案:

答案 0 :(得分:5)

一个鲜为人知的事实是,在这种情况下,$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范围内并自动完成。

答案 1 :(得分:0)

如果您愿意,也可以保留承诺的顺序,并根据您的情况传递null未申请的承诺。

当您的服务从来电者获得动态数量的购买请求并且命名不是一个选项时,这是另一种选择。

$q.all([null, huntersOrderPromise])
     .then(function(data){
       $scope.drawOrder = data[0]; // will be null
       $scope.hunterOrder = data[1];
     });