在for循环中进行同步HTTP调用
making synchrnous http call in a for loop angularjs
我有一个url数组,要求是我必须使http。以同步方式获取请求。只有在第一个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 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,延迟调用来实现这个
希望能有所帮助
相关文章:
- 如何制作'http请求'在Node js中同步
- 如何从node.js中的HTTP请求中获得同步结果
- 如何在nodejs中的async.each中进行同步http调用
- 如何在node.js中使用promise进行同步http调用
- Angular2:动态同步http请求
- 同步解决HTTP延迟承诺
- AngularJs:在内部调用$http或$resource时,让方法同步返回
- $http.获取同步 AngularJS
- 捕获失败的同步 HTTP 请求
- AngularJs:$http同步调用
- 默认情况下,大多数http请求是同步的吗?
- Angular $http的同步调用
- 如何使javascript等待,直到它得到一个有效的响应,从同步http请求
- 保持客户端与服务器端状态管理和http请求同步
- 使用$ q.所有这些都是为了让同步HTTP调用无法正常工作
- 在for循环中进行同步HTTP调用
- 带下划线的Angular同步http调用
- 使用可观察的两个同步 http 调用
- 如何在angular js中发布同步HTTP请求
- Jquery ajax同步HTTP请求