由于节点异步而难以查询数据库

Struggling with querying database due to node being asynchronous

这是我使用 Node.js 以及 sqlite3 的第一个项目。由于节点是异步的,我真的很挣扎,因为我有一个 .js 文件专门用于与我的数据库交互的函数。但这意味着每当我尝试调用这些函数并将它们分配给一个变量时,在我可以分配之前我尝试用变量 运行 做的事情。例如:

//From my .js file that handles server stuff
app.post('/login', function (req, res, next) {
    placeholder = loginVer("Test", "Test")
    console.log(placeholder) //Outputs pending promise
})

//From my database.js file
function databaseUserQuery(email){
    return new Promise(function (resolve,reject) {
        info = [] //empty array, if query can't find anything, info stays null which serves the purpose
        db.each("SELECT Email emailS, Password pword FROM Users WHERE Email  = ?", [email], (err, row) => {
            info[0] = row.emailS;
            info[1] = row.pword;
            resolve(info);
        })
        setTimeout(() => {
            resolve(info);
        },10)
    })
}

async function loginVer(email, password) {
    await databaseUserQuery(email).then(function(result) {
        if(result[0] == email){ //Checks if user exists (via email)
            if(result[1] == password){return(0)} //returns 0 if password matches
            else{return(1)} //Returns 1 if password is wrong but user exists
        } else {return(2)} //Returns 2 if user does not exist
    })
}

如果代码本身不好,我很抱歉,但我已经使用 promises 来确保在调用 loginVer 函数时,它首先进行查询,然后继续处理输出,但我确实 think/hope 有更好的方法。

很简单,你需要做的就是使用 .then!

app.post('/login', function (req, res, next) {
    loginVer("Test", "Test").then(placeholder => {
        // hey the promise is resolved now and we got data!
        console.log(placeholder);
        res.send(placeholder);
    })
})

此外,您没有正确返回数据。

function loginVer(email, password) {
  return new Promise(resolve => {
    await databaseUserQuery(email).then(function(result) {
      if (result[0] == email) { //Checks if user exists (via email)
        if (result[1] == password) {
          resolve(0)
          return;
        } //returns 0 if password matches
        else {
          rresolve(1)
        } //Returns 1 if password is wrong but user exists
      } else {
        resolve(2)
      } //Returns 2 if user does not exist
    })
  });
}

此外,我建议您查看 bcrypt。您似乎将密码存储在数据库中,这是一个巨大的安全风险!使用 bcrypt 散列密码,这样如果有人进入您的数据库,您的密码就不会泄露!

//changed handler to async function
app.post('/login', async function (req, res, next) {
    try {
        //you can use await here now
        let placeholder = await loginVer("Test", "Test")
        console.log(placeholder) //Outputs pending promise
    } catch (error) {
        //any error with throw or reject statement in underlying function calls will propagate here
        console.log(error)
    }
})

//From my database.js file
function databaseUserQuery(email) {
    return new Promise(function (resolve, reject) {
        info = [] //empty array, if query can't find anything, info stays null which serves the purpose
        db.each("SELECT Email emailS, Password pword FROM Users WHERE Email  = ?", [email], (err, row) => {
            if (err) {
                return reject(err)
            }
            info[0] = row.emailS;
            info[1] = row.pword;
            resolve(info);
        })
    })
}

async function loginVer(email, password) {
    //either user async await or use promise chaining. databaseUserQuery returns promise so we can use await here
    let result = await databaseUserQuery(email)
    if (result[0] == email) { //Checks if user exists (via email)
        if (result[1] == password) { return (0) } //returns 0 if password matches
        else { return (1) } //Returns 1 if password is wrong but user exists
    } else { return (2) } //Returns 2 if user does not exist
}
  • async/awaitthen/catch 可以互换。
  • 如果一个函数 returns 您可以使用 async/await 方式或 then/catch 方式来使用它。await databaseUserQuery(email).then(function(result) { 在此语句中,您将两者混合使用。
  • 总是用 try/catch.catch 捕获错误。这样调试问题会更容易。