Shubham Khatri Shubham Khatri - 1 month ago 6
Node.js Question

Return the result obtained when using oracledb npm package

I am using

oracledb npm package
to establish connection with the DB when creating a node.js backend API. I am able to obtain the result when I do
console.log(result.rows)


Below is the function code

getDbConnection: function(query) {

var connectInfo= [EnvConfig.getConnectionHostName(), EnvConfig.getConnectionPort()]; // Array of hostname and port
var connectHost = connectInfo.join(':'); // join hostname and port with ':'
var connectionAttr = [connectHost, EnvConfig.getConnectionSID()]; // hostname:port and SID
var connectString = connectionAttr.join('/'); // creating the connection string like 'hostname:port'
console.log(connectString);

// creating a oracle connection
oracledb.getConnection(
{
user: EnvConfig.getConnectionUserName(),
password: EnvConfig.getConnectionPassword(),
connectString: connectString
},
function (err, connection) {
if(err) {
console.log(err.message);
return;
}
connection.execute(
query, function(err, result) {
if(err) {
console.log(err.message);
return;
}
console.log(result.rows); // I get result here
return result.rows; // return result on success
}
);
}
);
}


I call the getDbConnection function from other file and when I console.log() like
console.log(getDbConnection(query))
. I get the result as undefined. How do I solve this.

Answer

you can't get your data like this. Return like this will not gonna work here

Since it works in async nature, you can do one thing to use a callback function to get that result like this

DbConnection: function(query,callback) {//pass callback as parameter 

  var connectInfo = [EnvConfig.getConnectionHostName(), EnvConfig.getConnectionPort()]; // Array of hostname and port
  var connectHost = connectInfo.join(':'); // join hostname and port with ':'
  var connectionAttr = [connectHost, EnvConfig.getConnectionSID()]; // hostname:port and SID
  var connectString = connectionAttr.join('/'); // creating the connection string like 'hostname:port'
  console.log(connectString);

  // creating a oracle connection
  oracledb.getConnection({
      user: EnvConfig.getConnectionUserName(),
      password: EnvConfig.getConnectionPassword(),
      connectString: connectString
    },
    function(err, connection) {
      if (err) {
        console.log(err.message);
        return callback(err);
      }
      connection.execute(
        query,
        function(err, result) {
          if (err) {
            console.log(err.message);
            return callback(err);
          }
          console.log(result.rows); // I get result here
          return callback(null,result.rows); // return result on success
        }
      );
    }
  );
}

And call like this

//Use your function with callback
getDbConnection(query,function(err,result){
  if(!err){
    console.log(result)
  }
})
Comments