为了回答你的问题,适用@abdulbarik岗位。
下面是其他的东西,你的实际代码:
- 削减你的请求转换功能
- 当您使用回调,使用它们来正确地返回错误。不要丢。
- 你并不需要把
_id
钥匙插进报价
备注:
- 由于您使用的是现在支持Node.js的ES6(大部分),使用它的。阅读简单,效率更高。
样品约回调和功能切。我让你做其余的是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
});
**感谢异步方法**对代码进行更改。我赞赏你解释的方式,然而应用@Shawon所示的异步并行 –