user11130182
user11130182

Reputation: 121

AngularJs $q.all is not working with for loop

I've below code and want to execute the function DisplayData() after the for loop completes only but the DisplayData() is executing along with for loop so the data is displaying after each iteration of the for loop item which is not excepted.

   var promises = [];
 //let promise = $q.resolve(); 
var itemId = ''; var flavorId = '';
 for (var b = 0; b <= $scope.flavorsrray.length - 1; b++) {  // 3
      itemId = $scope.flavorsrray[b].ITEM_ID; flavorId = $scope.flavorIDArray[a].FLAVOR_ID;
       promise = promise.then(() => {
          return  getItemDetails(Plant_Id, Week_ID, Area_Id, Itemtype, itemId, flavorId).then(function () {
                  ItemDtls = $scope.ItemDetails; 
                  alert(ItemDtls);  --> 
                      if (ItemDtls != null && ItemDtls != '' && ItemDtls.length > 0) {
            ..... doing some stuff here 
                }

             })                      
       });
    promises.push(promise);
  }
         $q.all(promises).then(function () {
         alert("done"); //---> this alert is executing before the  alert(ItemDtls);
         DisplayData();
        })
        // promise.then(() => { 
    //  alert("done"); ---> this alert is executing before the  alert(ItemDtls); 
    //  DisplayData() 
        // });

removed some code for better readability but it was displaying data.

tried in different ways as above and is there a way to come out of this issue?.

Upvotes: 0

Views: 117

Answers (1)

Petr Averyanov
Petr Averyanov

Reputation: 9486

I guess (as u didnt provide full code) that you want add return before getItemDetails:

promise = promise.then(() => {
            return getItemDetails(Plant_Id, Week_ID, Area_Id, Itemtype, itemId, flavorId)

this way resulting promise will wait for result of getItemDetails

Upvotes: 0

Related Questions