Async/await does not work within forEach loop in nodejs?

How to solve the problem of interacting with database or API within forEach loop in node js or is there any other way to loop 

through the array and solve this problem of fetching data from database/API in node js?

 

We have also faced such problem where we want to loop through array of objects and

further get a detailed information about user from user id and add this into all objects

respectively. I can explain with two examples where one works but the other does not:

 

1- Working example:

 

// Here info is the array of objects

var newArr = [];

if(info.length > 0){

    for(let element of info) {

        element = JSON.parse(JSON.stringify(element));

        if(element.sender_id != ''){

            // this function fetches user information from database which takes some moment

            var user = await this.getUserById(element.sender_id); 

            element.user = user[0];

            newArr.push(element);

        }

    }

}


 

2- Example does not work:

 

// Here info is the array of objects

var newArr = [];

if(info.length > 0){

    info.forEach(element => {

        element = JSON.parse(JSON.stringify(element));

        if(element.sender_id != ''){

            // this function fetches user information from database which takes some moment

            var user = await this.getUserById(element.sender_id); 

            element.user = user[0];

            newArr.push(element);

        }

    });

}

 

In second example you will get a blank array because forEach does not support 

async await feature of node js. So, we have to use "for of" which helps you 

to achieve your requirement as stated above. This same situation will work 

if you are working with APIs to get some information from other server.