Alex M. Alex M. - 3 months ago 9
MySQL Question

Cannot get return from module in nodejs + node-mysql

I got the following code on my localhost:

/model/company.js

var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'admin'
});

module.exports = {
get: function(){
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
return rows;
})
}
}


/routes/company.js

var Company = require('../models/company')


var express = require('express');
var router = express.Router();

router.route('/companies').get(function(req, res){

console.log(Company.get());
//res.json(Company.get());


})


I already tried some things, but I think this is how it should be.
But my
console.log
returns me
undefined
. I don't know what I'm doing wrong.

If I do:

connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
console.log(rows)
})


It works.

What do I need to do (or study)?

Answer

Your get function returns undefined because you don't specify a return value. You specify a return value for your callback function, but your outer function doesn't know or care about that. If you want the behavior you expect, you need to pass in a callback to your get function to have access to the rows variable.

Try this:

 module.exports = {
    get: function(callback){
        connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
            // A 'node-style' callback will usually be callback(error, value)
            callback(null, rows);
        })
    }       
}

Your console.log will work if you do this:

Company.get(function(error, rows){
  console.log(rows);
}

For a general overview of asynchronous behavior in javascript, check out this answer.