'showing empty array in after pushing data from foreach into it in asynchronous function
I'm new to async/await. when I print an array console.log shows an empty array [] but inside the loop, console.log shows data. Can somebody please help me where I'm going wrong.
commandbody.forEach(async (command) => {
const arrayC = await commandsModel.getbyId(command);
cmdArray.push(arrayC);
});
console.log(cmdArray);
Solution 1:[1]
The forEach function is not async-aware. You will need to use a simple for loop:
for( let i = 0; i < commandbody.length; i++ ) {
let arrayC = await commandsModel.getbyId(command);
cmdArray.push(arrayC);
}
console.log(cmdArray);
This should work if your outer function is marked as async too.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
