问题描述
在通过 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 语句在我的搜索发生之前运行。我这样做是因为如果没有找到电子邮件,我无法在搜索中找到返回某些内容的方法,并希望在发生此类事情时进行标记。
解决方法
您需要提供一个回调函数,以便在查询运行完成后运行。基于 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")}
});