title: In node.js, How to return mysql results from a function?
body: <p>I tried to separate function to another file, as the function fetching data from mysql database.</p>
  <p>This is <code>db.js</code></p>
  <pre><code>const mysql = require('mysql');
  
  var con = mysql.createConnection({
      host: &quot;localhost&quot;,
      user: &quot;root&quot;,
      password: &quot;&quot;,
      database: &quot;sample&quot;
  });
  
  con.connect()
  
  module.exports = function(query) {
      con.query(query, function (err, result) {
          if (err){
              console.log(err);
          } else{
              console.log(result)
              return result
          }
      });
  };
  </code></pre>
  <p>This is <code>main.js</code></p>
  <pre><code>const express = require('express')
  const db = require('./db')
  
  const app = express()
  
  app.get('/test', function(req, res){
      var sql = &quot;SELECT id FROM user&quot;
      console.log(db(sql))
      res.send(db(sql))
  });
  </code></pre>
  <p>In <code>main.js</code> on <code>console.log(db(sql))</code> got undefined.</p>
  <p>But in <code>db.js</code> on <code>console.log(result)</code> I got the values as:</p>
  <pre><code>[
    RowDataPacket { id: 1 },
    RowDataPacket { id: 2 },
    RowDataPacket { id: 3 }
  ]
  </code></pre>
  <p>Why did I get <code>undefined</code> in the main.js? Is there any solution for this issue?</p>