title: Nodejs MySQL connection query return value to function call
body: <p>I am trying get value from database. Trying it out with a demo example. But I am having problem to synchronize the calls, tried using callback function. I am beginner in node.js, so don't know if this is the right way.</p>
  
  <p>FILE 1 : app.js</p>
  
  <pre><code>var data;
  
  var db = require('./db.js');
  
  var query = 'SELECT 1 + 1 AS solution';
  
  var r = db.demo(query, function(result) { data = result; });
  
  console.log( 'Data : ' + data);
  </code></pre>
  
  <p>FILE 2 : db.js</p>
  
  <pre><code>var mysql      = require('./node_modules/mysql');
  
  var connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'root',
      password : 'root',
  });
  
  module.exports.demo = function(queryString, callback) {
      try {
          connection.connect();
          console.log('Step 1');
  
          connection.query(queryString, function(err, rows, fields) {
              console.log('Step 2');
              if (err) {
                  console.log("ERROR : " + err);
              }
              console.log('The solution is: ', rows[0].solution);
  
              callback(rows[0].solution);
  
              return rows[0].solution;
          });
          callback();
  
          connection.end();
          console.log('Step 3');
      }
      catch(ex) {
          console.log("EXCEPTION : " + ex);
      }
  };
  </code></pre>
  
  <p>OUTPUT :</p>
  
  <pre><code>Step 1
  Step 3
  Data : undefined
  Step 2
  The solution is:  2
  </code></pre>
  
  <p>Referred to this question also, but it didnt solve my problem :
  <a href="https://stackoverflow.com/questions/9651046/nodejs-return-value-from-callback">nodeJS return value from callback</a></p>