Currently, I am facing an issue with a loop in my client API. The loop is supposed to add data returned from an API call as an object to an object array in each iteration and then display the content of the object array at the end of the loop.
However, due to the asynchronous nature of JS code execution, when trying to display the content of the object array, it always returns undefined. I am seeking assistance in finding a solution to this problem. Your help would be greatly appreciated. Thank you.
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