javascript – Angular q所有动态结果

在做某事之前,我需要等待两个承诺才能解决.问题是,有时我只能根据客户的需要发送一个承诺,我需要依靠来自这个$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范围内并自动完成.

相关文章

最后的控制台返回空数组.控制台在ids.map函数完成之前运行va...
我正在尝试将rxJava与我已经知道的内容联系起来,特别是来自J...
config.jsconstconfig={base_url_api:"https://douban....
我正在阅读MDN中的javascript,并且遇到了这个谈论承诺并且不...
config.jsconstconfig={base_url_api:"https://douban....
这是我的代码main.cpp:#include<string>#include<...