Search code examples
javascriptnode.jspromisenode-mssql

Need to keep promise result in a variable for Nodejs mssql validation


    let RetrieveFromDb=(queryStr) =>
{
    let sql=require('mssql');
    let config={
        server:'127.0.0.1',
        database:'TestDB',
        user:'user',
        password:'user',
    };
    let dbConn=new sql.Connection(config);
    return dbConn.connect().then(function (){
        let request=new sql.Request(dbConn);
        return request.query(queryStr)
        .then(function(recordset)
        {
            return recordset;
            dbConn.close();

        }).catch(function (err) {
            console.log(err);
            dbConn.close();
        });
    }).catch(function (err)  {
        console.log(err);
    });
};


RetrieveFromDb("Select FirstName from User where UserID='1'").then(function(x){console.log(x[0].FirstName);});//console is displying the FirstName value from DB
RetrieveFromDb("Select FirstName from User where UserID='1'").then(res=>{console.log(res[0].FirstName)});//console is displying the FirstName value from DB

Above two function calls returning values to console, but I want to keep the result of RetrieveFromDb() to a variable, so that I can compare with other data for validation.

Let's say if var actualFirstname=RetrieveFromDb(myquery); then I'll compare if(actualFirstname===expectedFirstName) or not.


Solution

  • Promises are a method of code synchronization, so you have to treat their operations as asynchronous and use the values that you get when the promise resolves. There is no way to do:

    var actualFirstName = RetrieveFromDb(myquery);
    actualFirstName === expectedFirstName;
    

    Instead, you have to do the comparison when the promise resolves:

    RetrieveFromDb(myquery).then(data => {
      data.actualFirstName === expectedFirstName;
    });