[英]mongoose express node.js javascript function return undefined
function getPassword(uname)
{
User.findOne({'username': uname},{'password': 1}, function(err, cb)
{
console.log("print 2");
return cb.password;
});
console.log("print 1");
}
我是node.js的新手。 目前,我调用此函数时应该从mongodb返回密码。 但是,每当我调试时,我都意识到“print 1”总是在“print 2”之前打印,调用此方法并存储到变量的app.post函数总是返回“undefined”。
感谢是否有人可以向我解释。 谢谢!
这是因为回调内部会出现“print 2”。 当findOne完成它然后触发回调函数。
基本上,节点中的主事件循环触发User.findOne
,然后立即转到“print 1”。 然后稍后findOne
完成并触发你提供的回调函数,然后激活“print 2”。
@Alex Ford是对的。 在Node.js中,不应该有阻塞方法。 而是使用回调几乎所有:)
所以你的getPassword()
帮助器只需要一个参数callback [Function]
,它将在作业完成后调用。
function getPassword(uname, cb) {
User.findOne({'username': uname}, {'password': 1}, cb(err, data));
}
app.post('/somewhere', function (req, res, next) {
// ...
getPassword(username, function (err, password) {
if (err) return next(err);
console.log("I got '%s' password!", password);
});
});
tl; dr只需遵循嵌套的回调即可。 一般认为在异步方式不同步 :)
以上代码未经过测试,请先测试;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.