3
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!

2 Answers 2

2

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.findOne and then immediately moves on to "print 1". Then a bit later findOne finishes and fires the callback function you supplied, which then fires "print 2".

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I think I get what you mean.
Np. Don't forget to give me the green check mark if I answered your question ;)
0

@Alex Ford is right. In Node.js there should not be blocking approach. 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.

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. In general think in async way not sync :)

Code above isn't tested so please first test it ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.