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

1
  • Use array.map to avoid problems with closures inside loops. Commented May 6, 2019 at 11:02

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Added return as you mentioned, but still the alert("done"); was executing first and then displaying data along with for loop.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.