Trev
Trev

Reputation: 15

sqlite3 code not running in order while using nodejs

I've been learning about using sqlite3 as a dbms while developing through nodejs, specifically with express but I've been having problems as my code isn't running linearly?

    var emailD = null;
    var passwD = null;
    db.each("SELECT Email emailS, Password pword FROM Users WHERE Email  = ?", [email], (err, row) => {
        emailD = row.emailS;
        passwD = row.pword;
    });
    if(emailD == email){
        if(passwD == password){console.log("Correct")}
        else{console.log("Wrong PW")}
    } else {console.log("Email not found")}

Essentially my if statements run before my search happens. I am doing it like this as I couldn't find a way within the search to return something if an email wasn't found and wanted to flag when such a thing happened.

Upvotes: 1

Views: 108

Answers (1)

Brettski
Brettski

Reputation: 20091

You need to provide a callback function to run when the query has finished running. Based on the API Documentation the fourth parameter will handle this for you. Changing your code like so should get things running in the expected order.


var emailD = null;
  var passwD = null;
  db.each("SELECT Email emailS, Password pword FROM Users WHERE Email  = ?",
    [email], 
    (err, row) => {
      emailD = row.emailS;
      passwD = row.pword;
    }, 
    () => {
      if(emailD == email){
        if(passwD == password){
          console.log("Correct")
        } else {console.log("Wrong PW")}
      } else {console.log("Email not found")}
    });

Upvotes: 1

Related Questions