循环遍历Angular HTTP请求中的对象,在运行下一个循环之前等待响应

时间:2016-03-15 12:27:26

标签: javascript angularjs xmlhttprequest

我有这段代码:

// 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请求的任何帮助吗?

1 个答案:

答案 0 :(得分:1)

问题在于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数组。