0

我正在尝试在像这样的 _.each lodash 函数中在 Mongoose 查询中完成同步-

            let commentContainer = [];
            let comments = {..} //json object having comments
             _.each(comments, comment => {
                User.findOne({_id: comment.createdBy}).exec()
                .then(function(commentor){
                    var c = {
                        text: comment.text,
                        votes: comment.votes.length,
                        commentor: {
                            name: commentor.name,
                            profilePhoto: commentor.profilePhoto,
                            id: commentor._id

                        }
                    }
                    commentContainer.push(c);
                });
            });
            }
            console.log(commentContainer); //it shows []

我该如何实现它,我尝试通过延迟使用 setTimeout 函数,但它似乎不是一个有效的过程。

4

2 回答 2

0

这是因为 Node.js 是异步的。在处理 DB-call 或 Http 客户端调用等非阻塞调用时,应使用 async/await 或 promise 或回调。

      let comments = {..} //json object having comments
      console.log(findUSer(comments)); // print result


      async function findUSer(comments){
        let commentContainer = [];
         await _.each(comments, comment => {
            User.findOne({_id: comment.createdBy}).exec()
            .then(function(commentor){
                var c = {
                    text: comment.text,
                    votes: comment.votes.length,
                    commentor: {
                        name: commentor.name,
                        profilePhoto: commentor.profilePhoto,
                        id: commentor._id

                    }
                }
                commentContainer.push(c);
            });
        });
        }
         return commentContainer;
       }
于 2020-01-20T10:41:15.373 回答
0

像这样修改你的代码:

let fun = async() => {
  let commentContainer = [];
  let comments = {..} //json object having comments
  await _.each(comments, comment => {
    User.findOne({_id: comment.createdBy}).exec()
    .then(function(commentor){
        var c = {
            text: comment.text,
            votes: comment.votes.length,
            commentor: {
                name: commentor.name,
                profilePhoto: commentor.profilePhoto,
                id: commentor._id

            }
        }
        commentContainer.push(c);
    });
  });
  }
  console.log(commentContainer); //it shows []
}

当您需要在下一次迭代之前等待该过程完成时,使您的函数异步并使用 await keywoed

于 2020-01-20T10:01:07.600 回答