I wanna execute series of things in the same order for each item i have and collect the information then send statistics at the end.
here is the example code:
let listOfItems = [];
assignedItems.forEach(async (item) => {
let id = item.myID;
totalItemCount += await itemRepository.getItemCount(id);
let itemDetail = await itemRepository.getDetails(id);
listOfItems.push(item.name);
}, this);
console.log(listOfItems.length); // 0 ??
vs
let listOfItems = [];
for (let i = 0; i < assignedItems.length; i++) {
let id = assignedItems[i].myID;
totalItemCount += await itemRepository.getItemCount(id);
let itemDetail = await itemRepository.getDetails(id);
listOfItems.push(itemDetail.name);
}
console.log(listOfItems.length); // 5 as expected
output using foreach: 0 (because foreach is executed later) output using for: 5 as expected (because for is executed as code execution is written)
Main issue is: foreach is executed after my console.logs which are written after foreach as i want to collect first all the details for the items and then send the data i have collected.
What the hell is doing on? how do i fix the issue using foreach?