0

My Express app uses this controller method to call a model function verify, that looks up in the document database file with NeDB's find method. Here is the verify method..

verify : function(username, password) {
    db.find({ email: username }, function (err, docs) {
        return passwordHash.verify(password, docs[0].password);
    });
},

Here is the code that calls the function.

post_admin : function(req, res) {
if (!req.body.email || !req.body.password) {
    res.render('login', { title: 'Please provide your login details' });
  }else if(''!=req.body.email && ''!=req.body.password){
    var i = User.verify(req.body.email, req.body.password);
    if(i){
        res.render('admin/dashboard', { title: 'Successfully Logged In' });
    }else{
        res.render('login', { title: 'Not correct details!' });
    }
  }else{
    res.render('login', { title: 'Not correct details!' });
  }
},

...but it return false even if it matches data found in the file and should return true. When I console within the db.find method, it shows true but verify method returns false though. As a result the conditional block always executes the else part. When I console both I see the condition is executed before the db.find has logged anything. Is this due to asynchronous nature of programming? How should I handle this because I need to determine which view should be rendered within the controller! Is there a way to do this without breaking the asynchronous nature of Javascript here? Am I missing something obvious?

Smoking Sheriff
  • 471
  • 11
  • 23

1 Answers1

0

verify is async function, so I add callback

verify : function(username, password, callback) {
    db.find({ email: username }, function (err, docs) {
        callback(passwordHash.verify(password, docs[0].password));
    });
}
...
post_admin : function(req, res) {
    if (!req.body.email || !req.body.password) 
        return res.render('login', { title: 'Please provide your login and password details' });

    User.verify(req.body.email, req.body.password, function(isOk) {
        return (isOk) ?
                res.render('admin/dashboard', { title: 'Successfully Logged In' }) :
                res.render('login', { title: 'Not correct details!' });
    });
},
Aikon Mogwai
  • 4,954
  • 2
  • 18
  • 31