Abhishek Abhishek - 3 years ago 93
AngularJS Question

Angular asynchronous call is not ending while loop as expected



var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
for(var i=0;i<2;i++){
//var temp;
$http.get("https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js")
.then(function(response) {
console.log("inside");
// temp=10;
});
//while(temp!=10){}
console.log("outside")}
});

<!DOCTYPE html>
<html ng-app="myApp" ng-controller="myCtrl">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</html>





In this code i want to make print outside only after inside prints,mean unless i receive the response i want to make the loop wait and then go for second loop,for this i have defined a variable temp and i'm running a loop until its value becomes 10,but its going into infinite loop even after getting response (so commented )and setting temp value to 10.
Please help

Answer Source

You can first save the promise in a variable and then execute outside console inside the success of the promise. This will ensure that outside will be printed only once the inside promise resolves.

var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
    for(var i=0;i<2;i++){
       //var temp;
       var  q=$http.get("https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js")
      .then(function(response) {
          console.log("inside");
         temp=10;
       });
       q.then(function(res){
         while(temp!=10){}
         console.log("outside")
       })
       }
    });
<!DOCTYPE html>
<html ng-app="myApp" ng-controller="myCtrl">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</html>

The idea in below fiddle can be used if you want to abstract the code into different functions and then call it recursively.

Working Fiddle: http://jsfiddle.net/rmu6wuo8/1/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download