等待将未定义返回到异步函数(var all_courses未定义)

时间:2018-11-26 16:01:11

标签: node.js mongoose async-await

我正在尝试退回属于某个程序的课程。为此,我使用async / await,但它没有返回异步函数中以id发生的程序的过程:

程序控制器

function getProgram(req, res){
     var programId = req.params.id;

     Program.findById({'_id': programId}, (err, program)=>{

        if (err) return res.status(500).send({message: 'Petition failed'});

        if (!program) return res.status(404).send({message: 'There is not program to show'});

        getCoursesByProgram(programId).then((value) =>{
            return res.status(200).send({
                program,
                all_courses: value.all_courses
           });
        });
     });
 }

async function getCoursesByProgram(program_id){

     var all_courses = await Course.find({'program': program_id}).exec((err, courses)=>{
         if(err) return handleError(err);       
        return courses;
     });    
       return{
           all_courses: all_courses
     }
 }

模型

'use strict'

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var CourseSchema = Schema({

   title: String,
   video: String,
   creator: {type: Schema.ObjectId, ref: 'User'},
   program: {type: Schema.ObjectId, ref: 'Program'},
   description: String,
   created_at: String
});
module.exports = mongoose.model('Course', CourseSchema);


'use strict'

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ProgramSchema = Schema({

   title: String,
   creator: {type: Schema.ObjectId, ref: 'User'},
   image: String,
   description: String,
   created_at: String
});

module.exports = mongoose.model('Program', ProgramSchema);

请有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

当您将回调传递给.exec时,它将不再返回promise。相反,您可以使用promises进行错误/值处理:

try {
  return { all_courses: await Course.find({'program': program_id}).exec() };
} catch (err) {
  return handleError(err);       
}

请注意,除非getCoursesByProgram抛出错误,否则handleError将始终能够解决。


getProgram也可以是异步功能。您也可以合并错误处理,但是如果您想要更通用的错误处理,则必须要么独立捕获错误,要么以某种方式解析错误消息。

async function getProgram(req, res) {
  try {
    const programId = req.params.id;

    const program = await Program.findById({'_id': programId}).exec();
    if (!program) return res.status(404).send(...);

    const courses = await getCoursesByProgram(programId);
    return res.status(200).send({
      program,
      all_courses: value.all_courses,
    });
  } catch (err) {
    res.status(500).send({ message: 'Petition failed' });
  }
}