0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Looking good up until the product.push. 'resp.data' is undefined. If I console log the response I get the correct objects of data, the for loop isn't working as expected. Console logging 'resp' in the loop simply returns the object index number, (0,1,2,3,5). Any ideas?
actually, sorted it now. In the for loop had to do products.push(response[resp].data)
@Lovelock ok anyway I replaced the for( ..in..) loop with the traditional one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.