循环遍历 Angular HTTP 请求中的对象,等到响应后再运行下一个循环

Looping through objects in Angular HTTP request, wait until response before running next loop

本文关键字:循环 响应 下一个 再运行 对象 Angular 遍历 HTTP 请求      更新时间:2023-09-26

我有这个代码:

// 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