Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  83] [ 7]  / answers: 1 / hits: 6379  / 4 Years ago, fri, september 18, 2020, 12:00:00

I want to get the allItems variable outside the function, but I just can get an empty array. The first console.log shows the array I wanted, but the second it's just [].


var allItems = [];    
orderPads.forEach(async element => {

element.orders_fk.forEach(async elem => {

let itemsArray = await OrderedItem.find({ order_fk: elem });


itemsArray.forEach(async e => {

let temp = e.toObject();
const mesa = await Table.findById(element.mesa);
temp.mesa = mesa.name;

allItems.push(temp)
console.log(allItems)

})
})
});
console.log(allItems)

I've already looked for answers online, but nothing seems to work in this case. Thank you for the help!


More From » express

 Answers
-1

Async functions don't do what you think they do in forEach. Foreach will wait for every loop, but since it won't return a Promise, you can't actually wait for all loops (the forEach) to be done - the method will just return the current null immediately. Then you log that once. You might notice that your last log is logged first, and your others later, indicating that forEach was completed, but the loops completed later, and your array only filled up after your first log.


Personally, I would suggest using a for loop itself instead, which does not actually take you out of the async flow:




const allItems = [];   

for( const element of orderPads ){
for( const elem of element.orders_fk ){

const itemsArray = await OrderedItem.find({ order_fk: elem });

for( const e of itemsArray ){

const temp = e.toObject();
const mesa = await Table.findById(element.mesa);
temp.mesa = mesa.name;

allItems.push(temp)
console.log(allItems)

}

}}

console.log(allItems)




for loops are core constructs in Javascript, while forEach is in essence a simplistic wrapper for a for loop in Arrays that was never intended for asynchronous use.


[#2654] Tuesday, September 15, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
agustindejonm

Total Points: 738
Total Questions: 84
Total Answers: 84

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
agustindejonm questions
Fri, Jun 25, 21, 00:00, 3 Years ago
Sat, May 16, 20, 00:00, 4 Years ago
Thu, May 14, 20, 00:00, 4 Years ago
;