0

I want to fetch a variable from MySQL table and based on the variable value open my web app window. I coded the MySQL connection query at server end of the app. So when the server connection is established the above mentioned flow could happen. But after fetching the variable value, the code doesn't run forward and in debug mode the cursor ends on being the return value of y. Someone please help to resolve the issue. Thanks in advance.

#!/usr/bin/env node
'use strict';

require('dotenv').config({silent: true});

var server = require('./app');
var port = process.env.PORT || process.env.VCAP_APP_PORT || 8000;
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

var def = function(){
server.listen(port, function() {
  // eslint-disable-next-line
  console.log('Server running on port: %d', port);
  return;
});
}

var X;
global.x = X;

var mysql = require('mysql');
var mysqlPool  = mysql.createPool({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'emp',
  debug    : true
});

var abc = function(){
 mysqlPool.getConnection(function(err, connection) { 
  connection.query("select exp from empid where id= 12345", function(err, rows){
  if(err) {
    throw err;
   } else {
    var y = rows[0].exp;
   }
  //connection.release(); 
  *return y;*
  });
 });
}

def();
abc();

if(abc > 2) {
  window.location.href = "http://www.w3schools.com";
}
sourabh
  • 1
  • 2

1 Answers1

0

You cannot return the value from the callback because your abc() function returns way before your return statement is run - note that the return returns from the function in which it was used, not some outer function.

You can return a promise or use a callback if you want to use that value outside of the DB query handler.

See those answers for details:

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177
  • Thanks rsp that helped but now I have another issue. The socket is closing after the url is opened. I want socket to be opened so that i can continuously monitor DB and pop up url based on DB value. Please help. Thanks.var abc = function(callback){ mysqlPool.getConnection(function(err, connection) { connection.query(qry, function(err, rows){ if(err) { throw err; } else { var y = rows[0].exp; console.log(y); callback(y); } }); }); } def(); abc(function(y){ console.log(y); if(y > 2) { opn('http://www.w3schools.com'); } }); – sourabh Feb 08 '17 at 14:39