I am using NodeJS version v10.15.3 and I have a code something like this:
async getItems(): Promise<Array<any>> {
let retArray = [];
await some.list.forEach(async function (someObj) {
let item = new Item();
await item.initialize(someObj);
await retArray.push(item);
}
console.log("retArray="+JSON.stringify(retArray));
retrn retArray;
}
async mainFunction() {
let items = await getItems()
console.log("items="+JSON.stringify(items));
}
When I call the mainFunction()
, and when I log its result(the items
), it does contain the expected value. But the weird thing is that inside this getItems()
function, even with await
on forEach
(which adds an item to the retArray
), when I print the retArray
after the forEach
right before the function returns it, it doesn't have the full value in it. I await
for item to initialize
, and I even await for the item to be push
ed to the retArray
.
It just doesn't make sense that this log shows empty list
console.log("retArray="+JSON.stringify(retArray));
yet this log shows full list that I expect.
console.log("items="+JSON.stringify(items));
How can I make it so that after the forEach
, when I reference retArray
like below
console.log("retArray="+JSON.stringify(retArray));
the retArray
actually does contain the full data it gathered?