在 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 以与获取的顺序相同的顺序处理数据。
试试这个:
// 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
数组。
我有这个代码:
// 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 以与获取的顺序相同的顺序处理数据。
试试这个:
// 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
数组。