2017-07-25 62 views
1

角异步调用没有结束while循环如预期

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. 请帮忙

+0

你的意思是你想一次接一次地执行'get'调用3次吗? –

+0

我想循环等待,直到它得到响应,然后去第二个循环,但它是连续3次,然后我得到的回应 – Abhishek

+0

它应该像内部外部内部外部控制台 – Abhishek

回答

1

您可以先将承诺保存在变量中,然后在承诺成功的情况下在控制台外部执行。这将确保一旦内部承诺解决,外部将被打印。

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/

+0

我想,OP想按顺序调用他的循环,比如1 => 2 => 3.这意味着第二个Ajax应该在第一个完成之后调用并且在第二个完成之后调用第三个完成 –

+0

'while(temp!= 10){}'in您的代码可能会让浏览器冻结一段时间。在这种情况下,你应该'setInterval' – huydq5000

+0

@PankajParkar如果它的顺序,然后他可以使用上面的东西,就像链接承诺 – Vivz

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上心。