如何重复ajax调用,直到服务器返回特定值为止?

如何重复ajax调用,直到服务器返回特定值为止?,ajax,angularjs,Ajax,Angularjs,我需要填充progressbar,我有一个提供当前进度的服务。 我的想法是: $http.get('service').success(function(response, status, headers, config){ $scope.progress = response.progress; $scope.progressL = response.progress+"%"; if(response.progress < 100){

我需要填充progressbar,我有一个提供当前进度的服务。 我的想法是:

$http.get('service').success(function(response, status, headers, config){
         $scope.progress = response.progress;
         $scope.progressL = response.progress+"%";
         if(response.progress < 100){
             //repeat
         }
$http.get('service').success(函数(响应、状态、标题、配置){
$scope.progress=response.progress;
$scope.progressL=response.progress+“%”;
如果(响应进度<100){
//重复
}

只需将api调用放在函数中,让处理程序调用它:

function checkProgress(){
    $http.get('service').success(function(response, status, headers, config){
       $scope.progress = response.progress+"%";
       if(response.progress < 100){
           checkProgress();
       }
   }
}
每次“回调”之前,控制台都会说“返回”

当解析保证为异步时,您就没事了。下面是数千次解析异步的演示:

如果不是这样的话(例如,如果
$http
回调不保证被称为异步的话),那么您希望通过强制其异步来保护自己,如下所示:

function checkProgress(){
    $http.get('service').success(function(response, status, headers, config){
       $scope.progress = response.progress+"%";
       if(response.progress < 100){
           $timeout(checkProgress); // This will perform async
       }
   }
}
函数检查进度(){
$http.get('service').success(函数(响应、状态、标题、配置){
$scope.progress=response.progress+“%”;
如果(响应进度<100){
$timeout(checkProgress);//这将执行异步
}
}
}

您可以递归地调用它:


var callback=函数(响应、状态、标题、配置){
$scope.progress=response.progress;
$scope.progressL=response.progress+“%”;
如果(响应进度<100){
$http.get('service').success(回调);
}
};
$http.get('service').success(回调);

这很好,但它不会最终填满堆栈吗?不,外部函数会在回调触发之前完成并清除路径。异步的东西。添加了一节解释为什么堆栈会很好。
function checkProgress(){
    $http.get('service').success(function(response, status, headers, config){
       $scope.progress = response.progress+"%";
       if(response.progress < 100){
           $timeout(checkProgress); // This will perform async
       }
   }
}