预期输出:“x为2” 实际输出:“x未定义”
app.js
var x = db_Save(req.session.user);
console.log('x is ' + x);
dbFile.js
var db_Save= function (user) {
// return 2; /* 'x is 2' would print;
console.log('function returns "undefined" before following');
userProfile.find({Email: profileInstance.Email}, function(err, doc){
console.log('prints after "x is undefined"');
return 2; // does not get returned
});
}
答案 0 :(得分:3)
使用回调函数:
db_Save(req.session.user,function(x){
console.log('x is ' + x);
});
var db_Save= function (user,callback) {
userProfile.find({Email: profileInstance.Email}, function(err, doc){
callback(2);
});
};
答案 1 :(得分:1)
userProfile.find是异步的,这意味着它会被启动但直到你的console.log被触发后才返回2。你的回调就是这个功能:
function(err, doc){
console.log('prints after "x is undefined"');
return 2; // does not get returned
}
您将此作为调用userProfile.find
的第二个参数。当find完成时,该函数被称为返回2,但此时已经太晚了,你已经控制了当时未定义的console.logged x。