0

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?.

user11130182
  • 121
  • 10
  • Use [array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to avoid problems with closures inside loops. – georgeawg May 06 '19 at 11:02

1 Answers1

0

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

Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38
  • Added return as you mentioned, but still the alert("done"); was executing first and then displaying data along with for loop. – user11130182 May 06 '19 at 11:22