使用 nodejs 时,sqlite3 代码不是 运行

sqlite3 code not running in order while using nodejs

我一直在学习如何在通过 nodejs 进行开发时将 sqlite3 用作 dbms,特别是使用 express,但我一直遇到问题,因为我的代码不是 运行 线性的?

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

本质上是我的 if 语句 运行 在我进行搜索之前。我这样做是因为我无法在搜索中找到一种方法来 return 如果找不到电子邮件并且想在发生这种事情时进行标记。

当查询完成 运行ning 时,您需要向 运行 提供回调函数。基于 API Documentation 第四个参数将为您处理。像这样更改您的代码应该 运行 以预期的顺序得到结果。


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