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. Currently, I have this function when called should return the password from 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”.
Appreciate if anyone can explain to me. Thanks!
That is because “print 2” occurs inside the callback. When findOne finishes it then fires the callback function.
Basically the main event loop in node fires
User.findOneand then immediately moves on to “print 1”. Then a bit laterfindOnefinishes and fires the callback function you supplied, which then fires “print 2”.