0

I am creating a function that will return me the result of a DB query. The problem is when I am calling the main function, the query function within the main function(getSessionCode) is not getting executed first. I tried the Promise manager approach as well as the callbacks but none of those seems to be working.

Code:

dbConnectionObject = require('./DatabaseHandler.js');
  dbConnect = dbConnectionObject.getdatabaseConnection();
  var sessioncode;
  function getSessionCode(emailaddress){
      var queryBuild = "select <column name> from <table_name> where email="+ "\'"+ emailaddress +"\'";
      var responseArray;
      dbConnect.query(queryBuild,(err, res) =>{
      if(err)
          {
          console.log(err);
          }
      else if(res){ 
          responseArray=res.rows;`enter code here`
          dbConnect.end();       
          console.log(responseArray);
          return responseArray;
      }  
    });
  }
sessioncode = getSessionCode('gautam.pruthi@abc.com');
console.log(sessioncode);
  • Expected Result: The 2nd console.log statement(console.log(sessioncode)) should execute at the end. At the moment, the console.log statement within the query function is getting excuted first. – Gautam Pruthi Apr 15 '19 at 17:01
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – mbojko Apr 15 '19 at 17:03
  • Note the above is a server side code in Node.js – Gautam Pruthi Apr 15 '19 at 18:41

1 Answers1

0

Because dbConnect.query() use callback pattern to handle query result, this callback pattern block you to make query result as your function return value directly.

To resolve such problem, Promise came out to resolve callback pyramid.

1) change getSessionCode() to return a Promise
2) consume Promise eventual value with then() or await pattern

dbConnectionObject = require('./DatabaseHandler.js');
dbConnect = dbConnectionObject.getdatabaseConnection();
var sessioncode;

function getSessionCode(emailaddress) {
    var queryBuild = "select <column name> from <table_name> where email=" + "\'" + emailaddress + "\'";
    var responseArray;

    return new Promise(function(resove, reject){

        dbConnect.query(queryBuild, (err, res) => {
            if (err) {
                console.log(err);
                reject(err);

            } else if (res) {
                responseArray = res.rows;
                `enter code here`
                dbConnect.end();
                console.log(responseArray);

                resove(responseArray);
            }
        });

    });
}

sessioncode = getSessionCode('gautam.pruthi@abc.com');

sessioncode.then((session)=>{
    console.log(session);
})

sessioncode = await getSessionCode('gautam.pruthi@abc.com');
console.log(sessioncode);
yong
  • 13,357
  • 1
  • 16
  • 27