1

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.

4
  • 1
    How do you know? Commented Mar 7, 2021 at 4:59
  • I am assuming db.each() returns a promise (or is at least an async call) which needs to be resolved before you can run your if. Perhaps for the case of your code, but you if statement under where you are setting the emailD and passwD variables. Commented Mar 7, 2021 at 5:04
  • If you console.log the two values within the callback, do you see that in the wrong order? What you're saying shouldn't be possible, which of course does not mean it didn't happen.... Commented Mar 7, 2021 at 5:09
  • review, github.com/mapbox/node-sqlite3/wiki/…. Provide a callback function to run when your query is complete. Commented Mar 7, 2021 at 5:15

1 Answer 1

1

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")}
    });
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.