Golden Heart
Golden Heart

Reputation: 678

REST calls inside for loop in AngularJS

for (var i = 0; i < pricingPlans.length; i++) {
    productServices.retrivePricingPlan(pricingPlans[i].Id.Value).then(function (objPricingPlan) {
        productServices.createPricingPlan(objPricingPlan.data).then(function (objNewPricingPlan) {
            var newPlanID = objNewPricingPlan.data.PricingPlan.Id.Value;
            console.log("New ID");
            console.log(newPlanID);
            console.log("Old ID");
            console.log(product.PricingPlanAssociations[i].PricingPlanId.value);
            //  product.PricingPlanAssociations[i].PricingPlanId.value = newPlanID
        });
    });
}

I am making REST calls inside the for loop, but I want the REST calls to execute in following order:

  1. Retrieve pricing plan[i]
  2. Create pricing plan[i]
  3. Create product[i]

but when I look at the console tab they are executing in a different order

How can I ensure the pricing plans are executed in that particular order inside the for loop?

NOTE: retrivePricingPlan and createPricingPlan return calls to $http.post().

Network Tab

Upvotes: 0

Views: 297

Answers (1)

willoller
willoller

Reputation: 7330

Because the AJAX calls are all asynchronous, and the for loop is synchronous, the actual calls can be in any order. The "dependent" calls will be in the correct order, though. (That is, the promise chain will always call Retrieve before calling Create)

If you really need these to work in order, you can create a queue to manage the asynchronous call order.

Upvotes: 1

Related Questions