0

I am writing a simple script to retrieve a password from the table and validate in node.js Here is the script

module.exports = {
  login: function (email, pass) {
    var sqlite3 = require('sqlite3').verbose();
    var db = new sqlite3.Database('test.db');

    db.get("SELECT password FROM users WHERE user_email = ?", email, function(err, row) {
      if (err !== null) {
        console.log("An error has occured");
        return "error";
      } else if(row.password === pass) {
        console.log("success");
        return "success";
      } else {
        console.log("Incorrect password");
        return "failure";
      }
    });
  }
};

The console log statements are correct when the if else cases are evaluated. However the return value is undefined. I do not understand why the return value is undefined if the logging is done correctly.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Aaron Dufour Oct 12 '14 at 15:32

1 Answers1

1

You can't return values from a callback because doing so is meaningless. You have to pass in a callback to your login() function and call that with (err, result) inside your db.get() callback:

module.exports = {
  login: function (email, pass, cb) {
    var sqlite3 = require('sqlite3').verbose();
    var db = new sqlite3.Database('test.db');

    db.get("SELECT password FROM users WHERE user_email = ?",
           email,
           function(err, row) {
      if (err)
        return cb(err);

      cb(null, row.password === pass);
    });
  } 
};
mscdex
  • 104,356
  • 15
  • 192
  • 153