Reputation: 641
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)?
Upvotes: 2
Views: 1125
Reputation: 4401
The reason is because your get
function is calling an asynchronous function inside it. Where you're calling return rows
, it's actually returning the rows to the anonymous function not the get
function.
This is basically what you have:
module.exports = {
get: function(){
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
//This return is returning THIS function --^
return rows;
});
return; //You're not returning anything. So it's undefined like just calling return.
}
}
What you want:
/model/company.js:
...
module.exports = {
get: function(callback){
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
callback(rows);
})
}
}
/routes/company.js:
...
router.route('/companies').get(function(req, res){
Company.get(function (rows) {
console.log(rows);
});
})
Upvotes: 1
Reputation: 461
You need to return the json as follows
get: function(){
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
res.json(rows);
})
}
Upvotes: -1
Reputation: 1785
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.
Upvotes: 2