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

I have this code:

// 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');
});

The issue is that sometimes the product scope array items do not arrive always in the same order they are requested.

I need the products $scope to loop through the array and only when the response has been pushed to the array:

products.push(response.data);

that is finally assigned to the variable $scope.products.

Any help with modifying my current HTTP request?

Answers


The problem resides in the for loop, that is synchronous, containing asynchronous code. In practice there is no guarantee that the inner http.get processes data in the same order it is get.

Try this:

// 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');

  });

I suggest to use $q.all() to preserve the order of the http.get results. Look also that $scope.products is after the for loop that assigns data values to products array as you specified.


Need Your Help

SQL Query for records with ONLY one condition

sql

I have a table that features products with different media IDs. Most products have a number of media ID's like so:

Cordova / Phonegap All External Ajax Requests Returns 404

android jquery ajax cordova

I did have a Cordova 3.3 app, but yesterday i update the cordova and all my app plugins to v5.0 of apache cordova.