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

你。 提交于 2019-12-12 03:34:40

问题


    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.


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



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


来源:https://stackoverflow.com/questions/43019053/need-to-keep-promise-result-in-a-variable-for-nodejs-mssql-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!