Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading