I am making a simple API which have list of comment and want to push all comment into comments array of object.I am stuck in a problem since few days.It gives the comments on log inside callback function but not outside the callback function.How to solve the issue,thanks in advance. The code:
router.get("/scomment", (req, res) => {
const commentId = req.body.commentId;
const postId = req.body.postId;
let comments=[];
commentModel.findOne({ postId: postId, commentId: commentId }, (err, doc) => {
doc.comments.map((comment) => {
getUsers(comment.email).then((users) => {
comments.push({
users,
comment:comment.commentText
})
console.log(comments)
});
});
res.json(comments);
});
});
const getUsers = (email) => {
let user = [];
return new Promise(function (resolve, reject) {
setTimeout(function () {
userModel.findOne({ email: email }, (err, info) => {
resolve({
"name": info.name,
"email": info.email,
"profile": info.profile
});
});
});
});
};