简体   繁体   中英

sqlite3 callbacks (node.js)

I'm trying to compare an entered email on my website, to ones in the database to see whether it already exists. If it does, then the function returns false and an error is displayed.

var db = new sqlite3.Database('users_db.db');

db.get(
    "SELECT * FROM users WHERE useremail = ?", 
    [email], 
    function (err, rows) {
        if (rows == undefined ){
            global.returnvalue2 = false;
        }
    }
);

What I want is for the function to be run immediately after the selection, so that the returned value is false, and the user record is not created.

At the moment I realise that the callback is being called after everything, so its just making the selection and carrying on throughout the rest of the program until the end.

How can I check if there are any existing records with the same email?

Make use of the async features in javascript, so your code would look something like this;

var db = new sqlite3.Database('users_db.db');
function checkemail(email, cb) {
    db.get(
         "SELECT * FROM users WHERE useremail = ?", 
         [email],  
         function (err, rows) {
            if (err || rows == undefined ){
                cb("bad email", null)
            } else {
                cb(null,rows)
            } 
         });
}
function checkpassword(pw,cb) {....}
function checkclass(cls,cb) {....}

and then write you code like this;

checkemail(myemail, function(err,rows) {
    if (err) return alert(err);
    checkpassword(pw, function(err, msg) {
       if (err) return alert(err);
       checkclass(cls, function(err, msg) {
           if (err) return alert(err);
           alert("Congratulation you passed all the checks");
       });
    });
});

Here's a little one I made.

const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('iHacks.db');

function get_user_credentials (email, password)
{ return new Promise((rs, rj) => {
  function callback (err, User)
  {
    if (err) rj(err);
    rs(User);
  }

  db.get('select * from users where email=? and password=?', [email, password], callback);
}); }

function login (email, password)
{ return new Promise ((rs, rj) => {
  // Hashing the password.
  password = sha256(password + 'EzSalt');

  // Creating an Error
  const err = new Error('Email or password did not match!');

  // Callback functions
  function check (User)
  {
    rs(User);
  }      

  function fail (err)
  {
    rj(err);
  }

  // Getting the user credentials
  get_user_details(email, password).then(check).catch(fail);    

}); }

login()
  .then(/* Continue code */)
  .catch(err => {throw new Error(err); })
  ;

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