我想创建一个获取用户信息的函数。当我从函数返回数据时,它返回undefined
。当我在函数内部console.log
时,它返回所有用户数据。怎么了?
代码:
function user() {
var uid = socket.request.headers.cookie.uid;
var pwd = socket.request.headers.cookie.pass;
if (uid != undefined && pwd != undefined) {
models.user.findOne({
'_id': uid,
'password': pwd
}, function (err, user) {
console.log(user);
return (user) ? user : false;
});
} else {
return false;
}
}
console.log(user());
答案 0 :(得分:0)
你需要一个回调,这是初学者的基本问题
function user(callback) { // receives a callback
var uid = socket.request.headers.cookie.uid;
var pwd = socket.request.headers.cookie.pass;
if (uid != undefined && pwd != undefined) {
models.user.findOne({
'_id': uid,
'password': pwd
}, callback); // pass callback to mongoose
} else {
return callback(new Error("No uid")); // pass callback when no uid
}
}
user(function(err, userData) { // now you invoke fn to user function
// err is err from database or from new Error("No uid")
// userData is database User
if (err)
return console.log(err);
console.log(userData);
// userData should be used here
// for example. send this User by socket
// socket.emit('databaseUser', userData);
});