如需回答您的问题,请申请@abdulbarik 帖子。
这是关于您的实际代码的其他内容:
- 将您的请求分解为函数
- 当您使用回调时,请使用它们正确返回错误。不要扔。
- 您不需要将
_id 键放入引号中
备注:
- 因为您使用的是现在支持 ES6(大部分)的 node.js,所以请使用它。阅读更简单,效率更高。
关于回调和函数剪切的示例。我让你做剩下的 es6,瀑布处理......你可以看看 Promise 和 Async/Await 模式。
// Check if there is a student
function check_student(user_id, callback) {
Stud.findOne({
_id: user_id
}, function (err, stud) {
if (err) return callback(err, false);
// stud here can worth false
return callback(false, stud);
});
}
// Check if there is a prof
function check_prof(user_id, callback) {
Prof.findOne({
_id: user_id
}, function (err, prof) {
if (err) return callback(err, false);
// prof here can worth false
return callback(false, prof);
});
}
// Get Stud not Prof info
function check_user_info(user_id, callback) {
// Look if user_id match a stud
check_student(user_id, function (err, result) {
// We have an error
if (err) return callback(err, false);
// We have a student
if (result) return callback(false, result);
// Check if user_id match a prof
check_prof(user_id, function (err, result) {
// We have an error
if (err) return callback(err, false);
// We have a prof
if (result) return callback(false, result);
// No result at all
return callback(false, false);
});
});
}
你怎么称呼它
check_user_info(user_id, function (err, result) {
// ...
});
带有承诺的代码示例:
// Check if there is a student
function check_student(user_id) {
return new Promise((resolve, reject) => {
Stud.findOne({
_id: user_id
}, (err, stud) => {
if (err) return reject(err);
// prof here can worth false
return resolve(stud);
});
});
}
// Check if there is a prof
function check_prof(user_id) {
return new Promise((resolve, reject) => {
Prof.findOne({
_id: user_id
}, (err, prof) => {
if (err) return reject(err);
// prof here can worth false
return resolve(prof);
});
});
}
// Get Stud not Prof info
function check_user_info(user_id) {
return Promise.all([
check_student(user_id),
check_prof(user_id),
]);
}
check_user_info(user_id)
.then([
stud,
prof,
] => {
// Handle result
})
.catch((err) => {
// Handle error
});