在映射功能中使用异步等待

时间:2020-01-18 14:35:35

标签: javascript node.js express async-await

在我的Node Express应用中,我想获取一堂课的所有评论,并通过在每个评论中添加一个fullname字段来修改每个评论。为了获得用户的全名,我在findFullNameByUserId中定义了UserController.js函数。我在findAllCommentsByLessonId()中使用CourseController.js,如下所示。但是,当我使用它时,我总是得到一个空数组。如何在findFullNameByUserId中使用findAllCommentsByLessonId(),以便可以将fullname字段添加到每个注释对象?

CourseController.js

findAllCommentsByLessonId: async (courseId,lessonId,callback) => {
    Course.find({_id: courseId}, function(err, course) {
      if (err) {
        callback(err, null);
      } else {
        const lesson = course[0].lessons.filter(l => l._id !== lessonId)
        const comments = lesson[0].comments.map( async c => {
          try{
            const name = await UserController.findFullNameById(c.user)
            return (
              {
                userId: c.user,
                name: name,
                content: c.content
              }
            )
          }
          catch(err){
console.log(err)
          }
        })

// console.log(comments) --> This always prints [{}]
        callback(null, comments)   
    }
    });
  }

UserController.js

module.exports = {
    findFullNameById: async (userId) => {
        await User.find({_id: userId}, function(err, user) {
            if (err) {
                console.log(err)
            } else {
                return  user[0].name+" "+( user[0].lname ? user[0].lname : "") 

            }
          });
    }
}

3 个答案:

答案 0 :(得分:1)

CourseController.js中,您可以使用async-await,也可以使用callback

异步等待方式:

findAllCommentsByLessonId: async (courseId,lessonId) => {
    let course = await Course.findOne({_id: courseId});
    if (course){
        let lesson = course.lessons.find(l => l._id == lessonId);
        let comments = [];

        for(let comment of lesson.comments){
               let name = await UserController.findFullNameById(comment.user);
               comments.push({userId: comment.user,name: name,content: comment.content});
        }
      return comments;
    }else{
      return [];
      }
  }

回调方式:

findAllCommentsByLessonId: (courseId,lessonId,callback) => {
       Course.findOne({_id: courseId},function(err, course) {
          if (err) {
            callback(err, null);
          } else {
            let lesson = course.lessons.find(l => l._id == lessonId);
            let comments = lesson.comments;
                comments.map((comment)=>{

                  UserController.findFullNameById(comment.user).then(name=>{
                      return {userId: comment.user,name: name,content: comment.content};
                  });

               });
              callback(null, comments);
            }
        });
 }

答案 1 :(得分:0)

首先删除回调并为await实际使用Promise。您尚未指定find是什么,但是很可能这是一个支持诺言的现代图书馆。所以写

async function findAllCommentsByLessonId(courseId, lessonId) {
  const [course] = Course.find({_id: courseId};
  const lesson = course.lessons.find(l => l._id !== lessonId);
  const comments = lesson.comments.map(async c => {
    const name = await UserController.findFullNameById(c.user)
    return {
      userId: c.user,
      name,
      content: c.content
    };
  });
}

module.exports.findFullNameById = async (userId) => {
  const [user] = await User.find({_id: userId});
  return user.name + " " + (user.lname ? user.lname : "");
};

然后您会注意到comments不是用户数组,而是对用户的承诺数组,因此请将其包装在await Promise.all(…)调用中。

答案 2 :(得分:0)

正如@SuleymanSah所说,我尝试使用res = sh.values_get("D2:D"),它运行良好。出于他指出的确切原因,我认为这是正确的方法。以下是我的操作方式:

.populate