Javascript 使用$q.all进行不起作用的同步http调用angularjs
我遇到以下问题,无法继续。我尝试了一些在不同问题中发布的解决方案,但都没能奏效 在我的控制器中,我有一个$scope.init()函数。我有一个for循环,它调用一个函数来进行http。get调用不同的url,每个url取决于前一个调用的数据,所以我需要它是同步的Javascript 使用$q.all进行不起作用的同步http调用angularjs,javascript,angularjs,http,get,Javascript,Angularjs,Http,Get,我遇到以下问题,无法继续。我尝试了一些在不同问题中发布的解决方案,但都没能奏效 在我的控制器中,我有一个$scope.init()函数。我有一个for循环,它调用一个函数来进行http。get调用不同的url,每个url取决于前一个调用的数据,所以我需要它是同步的 $scope.init = function() { decodedURL = $routeParams.url; //evaluate some variables, ampIndex is > -1 her
$scope.init = function() {
decodedURL = $routeParams.url;
//evaluate some variables, ampIndex is > -1 here
for( var i=0; ampIndex > -1; ++i)
{
decodedURL = decodedURL.substring(ampIndex+1, decodedURL.length);
ampIndex = decodedURL.indexOf("&");
$scope.getNextList(i);
/* above function call makes the http.get call to the currentURL based on
decodedURL, and the data is stored in variable[i+1], so for the next
iteration, the calls should be synchronous
*/
$q.all(asyncCall).then(function (data) {var j;} );
/* I wrote the above dummy statement so that it is executed only after
http.get in $scope.getNextList() function is successful, but it is
not working
*/
}
};
$scope.getNextList = function(index) {
// $currentURL is calculated
var hello = _helpers.server.http($http, $scope.currentURL) {
.success( function(response) {
})
.error( fucntion(errResponse) {
});
asyncCall.push(hello);
};
我该如何解决这个问题呢?沿着这些思路做点什么怎么样
$scope.init=函数(){
对于(变量i=0;i<10;i++){
$scope.getNextList(i)//将调用推入数组
};
var指数=0;
函数makeCall(){
$scope.asyncCall[索引]
.成功(功能(数据){
if(索引<$scope.asyncCall.length-1){
控制台日志(索引);
指数+=1;
makeCall();
}
否则{
console.log(index);//最后一次调用
}
})
}
makeCall();
};
那么问题是调用不同步?可能是因为$q.all在for循环中…是的,调用是不同步的…我将$q保留在里面,因为在每次迭代中,都有一个http调用,这应该是同步的。为什么要使用$q.all,如果异步调用只包含一个承诺?或者您应该刷新asyncCall,使其仅包含1个承诺…在每次迭代中,一个承诺被推送到asyncCall中,对吗?您正在寻找顺序执行,而不是同步执行。
$scope.init = function ( ){
for (var i=0; i < 10; i++) {
$scope.getNextList(i) // push calls into array
};
var index = 0;
function makeCall() {
$scope.asyncCall[index]
.success(function(data) {
if (index < $scope.asyncCall.length - 1) {
console.log(index);
index += 1;
makeCall();
}
else {
console.log(index); // last call
}
})
}
makeCall();
};