1

I have the following function that gets a username and by making a query to mssql checks if already exists in databse. I want the checkForUsername() to return true if recordSet.recordset.length >= 1. How can I do that? I am a bit confused about async/await. Thanks.

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);
    });
}
1
  • your function can't return true (or any other value) as it's written to use Promises. You will have to chain things otherwise (maybe using a callback) Commented Feb 8, 2020 at 17:56

2 Answers 2

2

Of course I can't check if the following code works, but you can try rewriting your code for something like this:

const checkForUsername = async user => {
  try {
    const
      dbConn = new sql.ConnectionPool(config),
      sqlObj = await dbConn.connect(),
      query = `SELECT * FROM Admins WHERE username='${user}';`, // Note that creating a query explicitly is not recommended as it is vulnerable to SQL injection attack!
      recordSet = await new sqlObj.Request(dbConn)query(query),
      hasRecords = !!recordSet.recordset.length;
      
    return hasRecords;
  } catch (error) {
    console.log(error);
  } finally {
    dbConn.close();
  }
}

// Call it
(async () => {
  console.log(await checkForUsername('Jhon due');
})();

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot Nave! It works just fine with some changes. Below is the solution for someone having the same problem.
0
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'));
})();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.