Javascript 猫鼬用承诺保存并填充
我有以下的代码猫鼬已经与蓝鸟达成协议Javascript 猫鼬用承诺保存并填充,javascript,node.js,mongoose,promise,bluebird,Javascript,Node.js,Mongoose,Promise,Bluebird,我有以下的代码猫鼬已经与蓝鸟达成协议 function createNewCourse(courseInfo, teacherName) { var newCourse = new courseModel({ cn: courseInfo.courseName, cid: courseInfo.courseId }); return newCourse.saveAsync() .then(function (savedCo
function createNewCourse(courseInfo, teacherName) {
var newCourse = new courseModel({
cn: courseInfo.courseName,
cid: courseInfo.courseId
});
return newCourse.saveAsync()
.then(function (savedCourse) {
var newTeacher = new newTeacherModel({
na: teacherName,
_co: savedCourse._id // This would be an array
});
return newTeacher.saveAsync().then(function() {
return newCourse;
});
});
}
这是对我的问题的简化,但它很好地说明了这一点。我希望我的createNewCourse函数返回一个承诺,一旦解决,将返回新保存的课程,而不是教师。上面的代码可以工作,但并不优雅,也没有很好地使用承诺来避免回调地狱
我考虑的另一个选择是返回课程,然后进行填充,但这意味着重新查询数据库
有没有办法简化这个
编辑:我认为发布保存代码可能有用,但使用本机回调忽略了错误处理
function createNewCourse(courseInfo, teacherName, callback) {
var newCourse = new courseModel({
cn: courseInfo.courseName,
cid: courseInfo.courseId
});
newCourse.save(function(err, savedCourse) {
var newTeacher = new newTeacherModel({
na: teacherName,
_co: savedCourse._id // This would be an array
});
newTeacher.save(function(err, savedTeacher) {
callback(null, newCourse);
});
});
}
使用:
还记得链锁是如何工作的吗
.then(function() {
return somethingAsync().then(function(val) {
...
})
})
相当于忽略任何闭包变量:
.then(function() {
return somethingAsync()
})
.then(function(val) {
...
})
returnx与.thenfunction{return x;}简单等价
.then(function() {
return somethingAsync()
})
.then(function(val) {
...
})