0

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
        });
      });
    });
  });
};

1 Answers1

0

You need to wait on all the promises and then return the result of each promise as a merged array after they are done.

router.get("/scomment", (req, res) => {
  const commentId = req.body.commentId;
  const postId = req.body.postId;

 commentModel.findOne({ postId: postId, commentId: commentId }, (err, doc) => {
    const promises = doc.comments.map((comment) => {
       return getUsers(comment.email).then((user) => {
        return {
             user,
             comment: comment.commentText
         }
      });
    });

    Promise.all(promises).then((...comments) => res.json(comments))

  });
  
});

What you did before doesn't work because res.json(comments); is called before each of the getUsers networks calls return since the latter is asynchronous, your code won't wait for them unless you chain those statements to when the promises are made.

adsy
  • 8,531
  • 2
  • 20
  • 31