Search code examples
node.jsexpressforeachasync-awaites6-promise

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

  • 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.