简体   繁体   English

mongoose express node.js javascript函数返回undefined

[英]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");
}

I'm new to node.js. 我是node.js的新手。 Currently, I have this function when called should return the password from mongodb. 目前,我调用此函数时应该从mongodb返回密码。 However, whenever I debug, I realised that "print 1" is always printed before "print 2" and the app.post function that calls this method and store to a variable always return "undefined". 但是,每当我调试时,我都意识到“print 1”总是在“print 2”之前打印,调用此方法并存储到变量的app.post函数总是返回“undefined”。

Appreciate if anyone can explain to me. 感谢是否有人可以向我解释。 Thanks! 谢谢!

That is because "print 2" occurs inside the callback. 这是因为回调内部会出现“print 2”。 When findOne finishes it then fires the callback function. 当findOne完成它然后触发回调函数。

Basically the main event loop in node fires User.findOne and then immediately moves on to "print 1". 基本上,节点中的主事件循环触发User.findOne ,然后立即转到“print 1”。 Then a bit later findOne finishes and fires the callback function you supplied, which then fires "print 2". 然后稍后findOne完成并触发你提供的回调函数,然后激活“print 2”。

@Alex Ford is right. @Alex Ford是对的。 In Node.js there should not be blocking approach. 在Node.js中,不应该有阻塞方法。 Instead use callbacks for mostly everything :) 而是使用回调几乎所有:)

So your getPassword() helper just need one more argument callback [Function] which will be called after job is done. 所以你的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 Just follow nested callbacks and that'd be fine. tl; dr只需遵循嵌套的回调即可。 In general think in async way not sync :) 一般认为在异步方式不同步 :)

Code above isn't tested so please first test it ;) 以上代码未经过测试,请先测试;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM