Angular q all dynamic results

I need to wait for two promises to be resolved before doing anything. The problem is that sometimes I can only have one promise to send based on what the client wants and I need to count on the results that come from that $ q.all. How can I dynamically define vars?

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

      

+3


source to share


2 answers


A little known fact is that it $q.all

can also take an object rather than an array, which can make your life easier in this case:

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 are resolved in the object, so they are called, instead of having an array, you get a resolved object with properties, so instead of arr [0], which might not be okay, you allow. hunters or allowed .drawOrder. This solution simply embeds one level into $ scope and does it automatically.

+5


source


You can also keep the order of the promises if you like, and pass null

for the ones that weren't applied depending on your condition.

This is an alternative where your service receives a dynamic number of buy requests from the caller and naming is not an option.



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

      

0


source







All Articles