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.

1

1 Answer 1

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);
    });
  } 
};
Sign up to request clarification or add additional context in comments.

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.