角度异步调用没有按预期循环结束

时间:2017-07-25 05:07:51

标签: javascript angularjs

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>

在此代码中,我想在内部打印后打印,意味着除非我收到响应,我想让循环等待,然后转到第二个循环为此我已经定义了一个变量temp并且我正在运行一个循环,直到它的值变为10,但是即使在获得响应(如此评论)并将temp值设置为10之后它也会进入无限循环。 请帮忙

2 个答案:

答案 0 :(得分:1)

您可以先将promise保存在变量中,然后在promise的成功中执行外部控制台。这将确保只有在内部承诺解决后才会打印外部。

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>

如果你想将代码抽象成不同的函数然后递归地调用它,可以使用下面的小提琴中的想法。

工作小提琴http://jsfiddle.net/rmu6wuo8/1/

答案 1 :(得分:0)

当我找到你的时候,你想重复一个请求,直到你得到一个特定的值。也许这对你有用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();
});

通过answer获得了这个想法。