I am having a hard time figuring out the asynchronous behaviour of nested forEach() functions with node.js. I am not sure where I should create and return a promise and so on.
I have tried wrapping all the logic of the getFeed() function into a return new Promise(), but I think resolve is called before the nested forEach()'s are done.
friends = user_info.friends;
function GetFeed() {
let post_ids = [];
try {
friends.forEach(async function(friend_id) {
const posts = await db.collection('users').findOne(
{ _id: ObjectId(friend_id) },
{ projection: { posts: 1 }}
);
posts.posts.forEach(function(post_id) {
console.log(post_id);
post_ids.push(post_id);
});
});
return new Promise((resolve, reject) => {
resolve(post_ids);
});
} catch (err) {
return res.status(500).json({ error: 'Internal server error, unable to collection post ids from the database.' });
}
}
GetFeed()
.then((post_ids) => {
console.log(post_ids);
return res.status(200).json({ post_ids: post_ids });
})
the console.log() statements reveal that the GetFeed().then() executes before the console.log() statement in the inner forEach loop. I expect that the GetFeed().then() console.log would wait for the nest forEach logic to finish and then console.log the result.