1

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

Abhishek
  • 351
  • 1
  • 3
  • 18
  • Do you mean you want to run `get` call 3 times, one after the other? – Pankaj Parkar Jul 25 '17 at 05:10
  • i want loop to wait until it gets response and then go for 2nd loop,but it's going 3 times on a row then i'm getting response – Abhishek Jul 25 '17 at 05:11
  • it should come like inside outside inside outside on console – Abhishek Jul 25 '17 at 05:13
  • well, I don't understand you explanation about `test` value? Can you elaborate more on it? – Pankaj Parkar Jul 25 '17 at 05:15
  • What you want, I think, is impossible without ES7's async/await. You want the loop **to hold** until the call completes. It is impossible to hold it back. Even if you use promises, they will trigger parallel AJAX calls. – 31piy Jul 25 '17 at 05:26
  • Here i'm running a loop and inside i have a http call which returns a promise.I want promise values to be used inside loop(codes i haven't written here).But whats happening is before the promise returns the whole loop was getting executed,so i wanted the loop to wait until the promise returns and go further,so i used temp value which is undefined at starting and it starts executing the loop unless the temp value is set to 10 after promises returns(loop will b busy in while loop's looping until temp is set to 10,so it doesn't goes next loop[i.e.,from i=0 to i=1]),but while loop is going infinit – Abhishek Jul 25 '17 at 05:27
  • @31piy So whats the solution,i want in nodejs to update many values inside loop,but its updating only one value because of the same issue – Abhishek Jul 25 '17 at 05:29
  • @Abhishek You can wait for the first API request to resolve and then call the second one based on the condition that if first one resolved or not. Check the answer bewlow – Vivz Jul 25 '17 at 05:31
  • @Vivz,Thank you,but why while loop is going infinite? – Abhishek Jul 25 '17 at 05:32
  • Even after temp value got updated to 10,it should have ended the loop,isn't it? – Abhishek Jul 25 '17 at 05:33
  • But the below code is not going, if it was going then the browser should have crashed. – Vivz Jul 25 '17 at 05:34

2 Answers2

1

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/

Vivz
  • 6,625
  • 2
  • 17
  • 33
  • I guess, OP wants to call his loop in sequential order like 1 => 2 => 3. that mean 2nd ajax should call after first one completed and 3rd after 2nd complete – Pankaj Parkar Jul 25 '17 at 05:20
  • `while (temp != 10) {}` in your code might make the browser freeze for awhile. In this case, you should you `setInterval` – huydq5000 Jul 25 '17 at 05:22
  • @PankajParkar If its sequential,order then he can use the above thing just like chaining promises – Vivz Jul 25 '17 at 05:23
  • @Vivz exactly, but that would be kind of combination of closure + recursive function – Pankaj Parkar Jul 25 '17 at 05:24
0

When I got you right, you want to repeat a request until you get a specific value. Maybe this could work for you https://jsfiddle.net/jpf4c24m/2/

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

  $scope.request = function request(object) {
    var counter = 0;
    var deferred = $q.defer();

    var httpConfig = {
      method: 'GET',
      url: '/echo/json'
    }

    var doRequest = function() {
      counter++;
      var self = this,
        args = arguments;
      $http(httpConfig).
      success(function(data, status) {
        if (data.key == 'your_droid') {
          deferred.resolve('Woohoo!');

        } else {
          console.log('Not the droids you are looking for..');
          //this will re-call doRequest();
          args.callee.apply(self);
        }
      }).
      error(function(data, status) {
        //just fail already, it's not working
        if (counter > 5) {
          return deferred.reject('Couldnt reach server this time...');
        }

        //this will re-call doRequest();
        args.callee.apply(self);
      });

    }

    doRequest();

    return deferred.promise;
  }

  $scope.request();
});

got the idea by this answer.

Amacado
  • 630
  • 5
  • 20