Reputation: 3
I want to print "comments" elements in console with foreach, but when I push some elements in the array this elements are only visible for first foreach where I pushed them, outside this "comments" array is still empty. How can I solve this problem?
const Post = require('../models/post');
const Comment = require('../models/comment');
getpost: async (req, res, next) => {
const { post_id } = req.params;
const post = await Post.findById(post_id);
const comments_id = post._comment;
var comments = [];
comments_id.forEach(async id => {
comments.push(await Comment.findById(id));
console.log(comments) // The output are elements which exist in Comment model
});
console.log(comments); // The output is []
comments.forEach(comment => {
console.log(comment);
});
Upvotes: 0
Views: 84
Reputation: 350107
You are trying to output a result synchronously which is only assigned asynchronously:
comments_id.forEach( async id => {
comments.push(await Comment.findById(id));
console.log(comments) // The output are elements which really exist in
// Comment model
});
When the above code meets the await
, execution proceeds immediately with the next forEach
callback, ...etc, etc. All these callback functions return (a promise) when they meet await
. But none will have received the comment yet. And so the execution proceeds to what follows the whole forEach
block... which is where you try to output the array, ... which is still empty.
To make it work, use Promise.all
instead of the above code block:
comments = await Promise.all(comments_id.map( id => Comment.findById(id) ));
Upvotes: 3