Skip to content Skip to sidebar Skip to footer

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', passwor

Solution 1:

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

Solution 2:

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

Post a Comment for "Need To Keep Promise Result In A Variable For Nodejs Mssql Validation"