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>
在这段代码中,我只想在 inside 打印之后打印 outside,这意味着除非我收到响应,否则我想让循环等待,然后进行第二个循环,为此我定义了一个变量 temp 并且我正在运行一个循环直到它的值变为 10,但是即使在获得响应(如此评论)并将 temp 值设置为 10 之后它也会进入无限循环。 请帮忙
最佳答案
您可以先将 promise 保存在变量中,然后在 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>
如果你想把代码抽象成不同的函数,然后递归调用它,可以使用下面fiddle的想法。
工作 fiddle :http://jsfiddle.net/rmu6wuo8/1/
关于javascript - Angular 异步调用没有按预期结束 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45294346/