循环遍历 Angular HTTP 请求中的对象,等到响应后再运行下一个循环
Looping through objects in Angular HTTP request, wait until response before running next loop
我有这个代码:
// HTTP request
$http.get(dataSource).
then(function(data, status, headers, config) {
// Products array
var products = [];
// Loop through each array value
for (var slug in data.data){
var product = data.data[slug];
$http.get('content/products/' + product + '.json').then(function(response){
products.push(response.data);
$scope.products = products;
}).catch(function(){
console.log('there was an error');
});
}
}).catch(function(){
console.log('there was an error');
});
问题是,有时产品范围数组项并不总是以请求的相同顺序到达。
我需要产品$scope遍历数组,并且仅在响应被推送到数组时:
products.push(response.data);
最终分配给变量 $scope.products
.
修改我当前的 HTTP 请求有什么帮助吗?
问题出在 for 循环中,该循环是同步的,包含异步代码。实际上,不能保证内部 http.get 以与 get 相同的顺序处理数据。
试试这个:
// HTTP request
$http.get(dataSource).
then(function(data, status, headers, config) {
// Products array
var products = [];
// Loop through each array value
var promises = [];
for (var slug in data.data){
var product = data.data[slug];
promises.push($http.get('content/products/' + product + '.json'));
}
$q.all(promises).then(function(response){
for (var i=0,len = response.length;i<len;++i){
products.push(response[i].data);
}
$scope.products = products;
}).catch(function(){
console.log('there was an error');
});
}).catch(function(){
console.log('there was an error');
});
我建议使用 $q.all()
来保留 http.get 结果的顺序。另请注意,$scope.products
是在 for 循环之后,该循环将数据值分配给您指定的数组products
。
相关文章:
- 响应 JSONP 请求时循环的无限空的目的是什么
- 跟踪循环中触发的请求-响应
- 通过响应按钮单击更改表标题,其中行使用 JSTL for 循环更新
- 终止无响应/无限循环的WebWorker(Javascript)
- javascript中的Json响应没有正确循环
- 避免“;无响应脚本"foreach循环中的消息
- 将增量计数器连接到 JSON 响应循环中的数组选择器的末尾
- 循环遍历 AJAX 响应元素
- 设置超时可以保存我的循环函数不被视为无响应
- Node/Express - 如何等到 For 循环结束再使用 JSON 进行响应
- 循环遍历 Angular HTTP 请求中的对象,等到响应后再运行下一个循环
- 我可以使用 foreach 循环来发送 ajax 调用的响应吗?
- for 循环元素的执行时间比内部 AJAX 调用可以响应的要快
- 如何显示来自循环抓取的响应(Cheerio)
- Angular http GET循环使用新的URL作为响应
- 循环函数会导致它在 javascript 中无响应
- 如何使循环等待到ajax响应
- 如何循环收集来自 Facebook API 请求的响应
- 如果 ajax 响应包含 window.print,则它会循环
- 如何使用计时器设置循环,该计时器发出 ajax 请求,直到达到响应