0
angular.forEach(data, function (item, index) {  
   $http.get('https://users.tap.sanv.com/api/find/?q=email')
     .success(function(data1){
        apiResponseArray = data1;
        var found = false;  
        angular.forEach(apiResponseArray,function (item1, index1) {
           if(item1.email == item.user_id){
              found = true;
           }
        });
        if(found == false){
           $http.post('/removeUsers', {removeUser : item.user_id, action_by : action_by})
              .success(function(data){
               })
              .error(function(err) {
                 console.log(err);
              });   
        }
    });
}); 

What happens now is it hits the api, & since the response takes time, the next iteration begins & continues.

Indranil Mondal
  • 2,799
  • 3
  • 25
  • 40
Indu
  • 11
  • 3
  • How you next iteration is beginning? Here I can see the forEach loop is within the success callback. That means if there is success then only the loop will run. – Indranil Mondal Sep 08 '16 at 09:33

1 Answers1

0

This is the solution to your problem and I have referenced following URLs for the same : 1. AngularJS - wait for multiple resource queries to complete 2. http://andyshora.com/promises-angularjs-explained-as-cartoon.html. Please use the function "multipleCalls" to trigger the sequence of request . Also feed in the "data" array with desired values .

var myApp = angular.module("myApp",[]);
myApp.controller('MasterDetailCtrl',function ($scope,$http,emailService,$q) {

var promises = new Array();    
var data = [1,2,3,4];

$scope.multipleCalls = function(){
    angular.forEach(data, function (item, index) {  
            promises.push( emailService.getEmails(data[index]));
        }); 


$q.all(promises).then(function(data) {
        apiResponseArray = data;
        var found = false;             
        angular.forEach(apiResponseArray,function (item1, index1) {
                console.log(angular.toJson(item1));
         });
     });
    }
}); 

myApp.factory('emailService', function ($http, $q) {
return {
    getEmails: function(id) {
        return $http.get('https://users.tap.sanv.com/api/find/?q=email:'+id)
            .then(function(response) {
                if (typeof response.data === 'object') {
                    return response.data;
                } else {
                    // invalid response
                    return $q.reject(response.data);
                }

            }, function(response) {
                // something went wrong
                return $q.reject(response.data);
            });
    }
  };
});
Community
  • 1
  • 1
Amit
  • 182
  • 3
  • 3
  • 12