我如何让我的 javascript 函数在继续之前等待 WebSql 事务完成

How i make my javascript function wait to WebSql transactions to finish before continuing

我创建了一个验证函数来查看该值是否在数据库中 table。尽管该函数始终 return 为真,即使该值存在于 table 中也是如此。我还尝试通过仅更改变量值来 return false,但这不会等待它,所以函数 returns 立即到 "if" 然后 alert("Not in use")

function Rval(Username,Displayname,Email){

    db.transaction(function (tx) { 
        tx.executeSql("SELECT UserName FROM Users WHERE UserName='" + Username.value + "'", [], function (tx, results) { 
            if (results.rows.length > 0) {
                return false
            }
        }, null);
        tx.executeSql("SELECT Email FROM Users WHERE Email='" + Email.value + "'", [], function (tx, results) {  
            if (results.rows.length > 0) {
                return false
            }
        }, null);
        tx.executeSql("SELECT DisplayName FROM Users WHERE DisplayName='" + Displayname.value + "'", [], function (tx, results) {  
            if (results.rows.length > 0) {
                return false
            }
        }, null);
    });
}



if (Rval(Username,Displayname,Email))
{
    alert("Not in use")
}
else
{
    alert("In use")
}

你可以说你的函数将return一个Promise

return new Promise((resolve, reject) => {
tx.executeSql("SELECT UserName FROM Users WHERE UserName=?", Username.value, (tx, results) => {
  if(results.rows.length > 0 {
  return resolve(false)
  //or return reject(new Error(error)) for errors
 }
}

类似这样。

const userQ = ({field, value, tx}) => 
    new Promise((resolve) => 
        tx.executeSql(`SELECT ${field} FROM Users WHERE ${field}='${value}'`, [], (tx,results) => resolve(!results.rows.length), null))

const getTx = (db) => new Promise((resolve) => db.transaction((tx) => resolve(tx)))

async function inUse(userName, displayName, email) {
    const tx = await getTx(db)
    const [a,b,c] = await Promise.all([
        userQ({field:'UserName', value:userName, tx}),
        userQ({field:'DisplayName', value:displayName, tx}),
        userQ({field:'Email', value:email, tx})
    ])
    return a && b && c
}

inUse(username, displayname, email).then((result) => {
    if (result) {
        alert("Not in use")
    } else {
        alert("In use")
    }
})