简体   繁体   中英

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. 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.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".

@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 ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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