【问题标题】:Looping through objects in Angular HTTP request, wait until response before running next loop循环遍历Angular HTTP请求中的对象,等到响应再运行下一个循环
【发布时间】:2016-03-15 23:02:46
【问题描述】:

我有这个代码:

// 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 请求有帮助吗?

【问题讨论】:

    标签: javascript angularjs xmlhttprequest


    【解决方案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 数组。

    【讨论】:

    • 谢谢!看起来不错,直到 product.push。 'resp.data' 未定义。如果我控制台记录响应,我得到正确的数据对象,for 循环没有按预期工作。循环中的控制台日志记录“resp”仅返回对象索引号 (0,1,2,3,5)。有什么想法吗?
    • 其实,现在整理好了。在for循环中不得不做products.push(response[resp].data)
    • @Lovelock 好吧,我用传统的循环替换了 for(..in..) 循环。
    猜你喜欢
    • 2016-10-24
    • 2017-10-27
    • 2019-02-11
    • 2021-11-07
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多