service call inside loop doesn't stops loop even if condition is false

520 views Asked by At

I want to stop repeated call to getModelData if shouldPermit becomes true. But below code always prints why I got printed forEach newlySelectedUsers in console for each newlySelectedUsers.

var shouldPermit = false;
angular.forEach(newlySelectedUsers, function(value, key) {
if(!shouldPermit) { 
console.log("why I got printed forEach newlySelectedUsers")                         
userService.getModelData($scope.$root.test[value].id)
.success(function (data) {                                
    if(lodash.isEmpty(data)) {                                      
        shouldPermit = true;
        $scope.insertSaving();
     }
       });                           
         }                      
          });

How to stop calls to getModelData once shouldPermit becomes true?

2

There are 2 answers

0
korteee On BEST ANSWER

That's because all the http requests run asynchronusly. That beeing said your itteration runs faster than the time needed for service to find (in your case) an empty data variable .

An option is to recursively call the http request:

const totalNewlySelectedUsers = newlySelectedUsers.length;


function getUser(idx) {

    let value = newlySelectedUsers[idx];

    userService.getModelData($scope.$root.test[value].id)
        .success(function (data) {
            if (lodash.isEmpty(data))
                $scope.insertSaving();
                return;
            }

            if(idx === totalNewlySelectedUsers) return;

            getUser(idx + 1);
        });

}

getUser(0);
1
Yuva Raj On

It's because of Asynchronous. The second iteration doesn't wait for userService.getModelData() called for first iteration to finish. So, you get console message even before it goes the success function of first iteration's userService.getModelData() where you change the shouldPermit to true.

Instead, you just move shouldPermit = true; to top to solve the issue.

var shouldPermit = false;
angular.forEach(newlySelectedUsers, function(value, key) {
if(!shouldPermit) 
{ 
  console.log("why I got printed forEach newlySelectedUsers");
  shouldPermit = true; <--- Moved from success function                  
  userService.getModelData($scope.$root.test[value].id) <--- Async Call
  .success(function (data) {                                
    if(lodash.isEmpty(data)) 
    {                                      
        $scope.insertSaving();
     }
     });                           
     }                      
   });