在执行ExecuteSQL函数之后,我会得到未定义的。登录函数使用ExecuteSQL函数用于检查用户是否存在?我在运行这个文件时遇到以下错误。异步等待。
“nodemon”因更改而重启...>[nodemon]开始节点dl.js
>未定义>未定义>指示符1
async function ExecuteSQL(strSQL) {
try {
const pool = await getConnection();
if (pool) {
const result = await pool.request()
.query(strSQL, async function (err, sqlResult) {
if (err) {
console.log(err);
}
else {
// console.log(strSQL);
// console.log(sqlResult);
return sqlResult;
}
});
}
else console.log(pool);
} catch (err) {
console.log(err);
}
};
async function login(strUID) {
const strSQL = `SELECT fUserPwd FROM tblUser WHERE fUserID ='${strUID}'`;
try {
const result = await ExecuteSQL(strSQL).then(function (data) {
console.log(data);
return data
});
console.log(result);
console.log('indicator1')
} catch (err) {
console.log(err);
}
};
login('ADMIN');
您没有从ExecuteSQL返回任何内容。此外,不应将async/await
与回调混合使用。您不应该将async/await
与混合使用。然后()
决定您更喜欢哪一个,并坚持您的决定。
你只要做
async function ExecuteSQL(strSQL) {
try {
const pool = await getConnection();
//you don't need to check for the pool, because getConnection() will throw if there is an error
const result = await pool.request().query(strSQL);
return result;
} catch (err) {
console.log(err);
}
};
async function login(strUID) {
const strSQL = `SELECT fUserPwd FROM tblUser WHERE fUserID ='${strUID}'`;
try {
const result = await ExecuteSQL(strSQL);
console.log(result);
return result;
} catch (err) {
console.log(err);
}
};
而且您不应该使用字符串连接或字符串模板来构造查询,因为这样很容易出错并且不安全。有关如何创建参数化查询,请参阅mssql手册。