1

I have the following loop which I have to make on my client API. On each iteration of loop I must add data returned from the API call as an object to an object array, then at the end of the loop I need to display the content of the object array.

Due to the nature of JS code execution (asynchronous) displaying the object array content always return undefined, so I was wondering if someone can please help me with a solution to this problem. Thanks.

  var invoiceObj = {};
  var invoiceObjArray = [];
  for (var i=0; i< 5; i++)
  {
      //getAllInvoices returns a promise from $http.GET calls...
      ClientInvoiceService.getAllInvoices(i).then(function(invoice){

             invoiceObj = { invoiceNum: invoice.Result[0].id,
                            clientName: invoice.Result[0].clientName};

             invoiceObjArray.push(invoiceObj);   

         }, function(status){
            console.log(status);
         });

  }

  console.log(invoiceObjArray[0]); //return undefined
  console.log(invoiceObjArray[1]); //return undefined

1 Answer 1

3

What you'll need to do is store all promises and then pass these to $q.all (scroll all the way down), which will wrap them in one big promise that will only be resolved if all are resolved.

Update your code to:

var invoiceObj = {};
var invoiceObjArray = [];
var promises = [];
for (var i=0; i< 5; i++)
{
      //getAllInvoices returns a promise...
      promises.push(ClientInvoiceService.getAllInvoices(i).then(function(invoice){

             invoiceObj = { invoiceNum: invoice.Result[0].id,
                            clientName: invoice.Result[0].clientName};

             invoiceObjArray.push(invoiceObj);   

         }, function(status){
            console.log(status);
         }));

}
$q.all(promises).then(function(){
    console.log(invoiceObjArray[0]);
});

This Egghead video is a nice tutorial to using $q.all:

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

2 Comments

Thanks a lot, $q.all solved the problem instantly :)
Great, glad to have helped!

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.