1

I have problem with my AngularJS function. Data from first forEach is retrieved with $http.get and in second forEach, $scope.products isn't defined yet. I know that $http.get() is an asynchronous request and this is the point... But how to rewrite this function to work fine ?

$scope.getAll = function () {
    var cookies = $cookies.getAll();
    $scope.products = [];
    var i = 0;
 angular.forEach(cookies, function (v, k) {
     console.log("important1:" +  $scope.products);
        console.log("key: " + k + ", value:  " + v);
         ProductsService.retrieve(k).then(function(response) {
                    $scope.products = $scope.products.concat(response.data);
                        $scope.products[i].quantity = v;
                        i++;
         }, function (error) {
            console.log('error');
         });
  });
    console.log("important2:" +  $scope.products);

    angular.forEach($scope.products, function(value, key) {
        $scope.total = value.quantity*value.price + $scope.total;
        console.log("Quantiy: " + value.quantity);
        console.log("Price: " + value.price);
    });
    console.log($scope.products);
    console.log($scope.total);
};
1
  • 1
    Put all ProductsService.retrieves in an array of promises and resolve using $q.all([promises]).then(...). Commented Sep 8, 2015 at 19:05

2 Answers 2

1

I suggest that you use the $q.all().

More specifically, you would do:

$q.all([p1, p2, p3...]).then(function() {
    // your code to be executed after all the promises have competed.
})

where p1, p2, ... are the promises corresponding to each of your ProductsService.retrieve(k).

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

Comments

0

Build up a list of service calls then call $q.all. Inside the then function you can put your second loop.

var listOfServiceCalls = [];
//Add to list of service calls

$q.all(listOfServiceCalls)
    .then(function () {
        //All calls completed THEN
            angular.forEach($scope.products, function(value, key) {
        $scope.total = value.quantity*value.price + $scope.total;
    });
});

Comments

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.