在 for 循环中进行同步 http 调用 angularjs
making synchrnous http call in a for loop angularjs
我有一个 url 数组,要求是我必须以同步方式发出 http.get 请求。只有在第一个 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 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,延迟调用来实现这个
希望对您有所帮助
我有一个 url 数组,要求是我必须以同步方式发出 http.get 请求。只有在第一个 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 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,延迟调用来实现这个
希望对您有所帮助