Javascript获取内部函数的返回值
我有以下函数获取用户名,并通过查询mssql检查数据库中是否已经存在。如果Javascript获取内部函数的返回值,javascript,sql-server,Javascript,Sql Server,我有以下函数获取用户名,并通过查询mssql检查数据库中是否已经存在。如果recordSet.recordSet.length>=1,我希望checkForUsername()返回true。我该怎么做?我对异步/等待有点困惑。谢谢 function checkForUsername(UserIn) { var dbConn = new sql.ConnectionPool(config); dbConn.connect().then(function () { v
recordSet.recordSet.length>=1,我希望checkForUsername()
返回true。我该怎么做?我对异步/等待有点困惑。谢谢
function checkForUsername(UserIn) {
var dbConn = new sql.ConnectionPool(config);
dbConn.connect().then(function () {
var request = new sql.Request(dbConn);
request.query("SELECT * from Admins WHERE username='"+UserIn+"';").then(function (recordSet) {
console.log(recordSet.recordset.length);
if(recordSet.recordset.length >= 1)
//checkForUsername return true
dbConn.close();
}).catch(function (err) {
dbConn.close();
});
}).catch(function (err) {
console.log(err);
});
}
当然,我无法检查以下代码是否有效,但您可以尝试为以下内容重写代码:
const checkForUsername=async user=>{
试一试{
常数
dbConn=新的sql.ConnectionPool(配置),
sqlObj=await dbConn.connect(),
query=`SELECT*FROM Admins,其中username='${user}';`,//注意,不建议显式创建查询,因为它容易受到SQL注入攻击!
记录集=等待新的sqlObj.Request(dbConn)查询(query),
hasRecords=!!recordSet.recordSet.length;
返回记录;
}捕获(错误){
console.log(错误);
}最后{
dbConn.close();
}
}
//叫它
(异步()=>{
日志(等待checkForUsername('jhondue');
})();
您的函数无法返回true(或任何其他值),因为它是为使用承诺而编写的。您必须以其他方式(可能使用回调)链接内容。非常感谢您的帮助!只需做一些更改,它就可以正常工作。下面是针对有相同问题的人的解决方案。
const checkForUsername = async UserIn => {
try {
var dbConn = new sql.ConnectionPool(config);
const sqlObj = await dbConn.connect();
const recordSet = await new sql.Request(dbConn).query(`SELECT * FROM Admins WHERE username='${UserIn}';`);
const hasRecords = !!recordSet.recordset.length;
return hasRecords;
}catch (error) {
console.log(error);
}finally{
dbConn.close();
}
}
// Call it
(async () => {
console.log(await checkForUsername('John'));
})();