Javascript 在for循环angularjs中进行同步http调用
我有一个url数组,要求我必须以同步方式发出http.get请求。只有在第一个url调用成功后,才应该调用第二个urlJavascript 在for循环angularjs中进行同步http调用,javascript,angularjs,http,get,Javascript,Angularjs,Http,Get,我有一个url数组,要求我必须以同步方式发出http.get请求。只有在第一个url调用成功后,才应该调用第二个url for(var i in urlArray) { /*do some operations and get the next url*/ $scope.alpha(newURL); } $scope.alpha = function (newURL) { $http.get(newURL) // these calls should be synchr
for(var i in urlArray)
{
/*do some operations and get the next url*/
$scope.alpha(newURL);
}
$scope.alpha = function (newURL) {
$http.get(newURL) // these calls should be synchronous
.success(function () {
})
.error(function () {
});
}
我该怎么做呢?看起来您真正想要的是按顺序进行调用,而不一定是同步的 在这种情况下,不要使用循环(因为它是同步的)。只需拨打下一个电话以响应上一个电话 简化示例:
var i = 0;
makeRequest(urlArray[i], function success() {
var nextURL = urlArray[++i];
if (nextURL) {
makeRequest(nextURL, success);
}
});
其中,makeRequest
是发出Ajax请求并在成功时调用回调的函数:
function makeRequest(url, callback) {
$http.get(url).success(callback);
}
我假设您希望按顺序调用它们,在这种情况下,您可以使用递归之类的方法,调用.success回调函数中的函数
var currentURL; // calculate teh currentURL
$scope.alpha(currentURL);
$scope.alpha = function (newURL) {
$http.get(newURL) // these calls should be synchronous
.success(function (response, status, headers, config) {
//get the response
//generate the new currentURL as per your need
//keep a break condition, to exit
$scope.alpha(currentURL);
})
.error(function () {
});
}
2) 或者,您可以使用$q、延迟调用来实现这一点
希望这对我如何定义makeRequest有所帮助?语法,我的意思是。。。。通过上面的代码,我得到了“ReferenceError:makeRequest未定义”,就像您定义任何其他函数一样,例如
函数makeRequest(url,callback){…}
。你可以随意命名,这只是一个例子。你必须用函数的代码替换…
。在那里,我更新了我的答案。我没想到定义函数会有这么大的问题。你试过使用$q吗?