Rocky
Rocky

Reputation: 897

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.

Upvotes: 0

Views: 1083

Answers (2)

Aaron Reese
Aaron Reese

Reputation: 554

Thanks guys, I have geen going round in circles for days trying to get my head around the async nature of the code. For me the lightbulb moment is that you have to set the variable value as part of the callback/promise stack (i.e. assign it within the function) My background is Excel, VBA, Sequel Server, PHP oop, C#. In all of these languages a function is something which runs a discreet piece of code and returns a value which is then assigned to the object on the left of the equasion.

function myFunc(){ return 'Hello World'}

var myvar =   myFunc() // sets myvar to 'Hello World'

In the land on Node you have to do the assignement IN the function

function myFunc(){ myvar = 'Hello world'}

So to get data from the database:

fetchFromDB('Select top 10 * from x',(err,res) =>{ myvar1 = res})
fetchFromDB('Select top 10 * from Y',(err,res) =>{ myvar2 = res})

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191779

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;
});

Upvotes: 1

Related Questions