Reputation: 29
I seperate the sql query and router file into two, trying to apply MVC concept. But why can I pass the result of the query? it doesn't work now, the console printed "undefine" instead of the results
//homeapi.js under folder api
var mysql = require('../conf/db');
let getAll = {};
getAll.all = () => {
var userGetSql = 'SELECT * FROM product';
mysql.query(userGetSql, (err, results) => {
if (err) {
return ;
}
return results;
})
}
let info = getAll.all();
console.log(info)
module.exports = getAll;
//index.js under routers file, I try to import it, but also failed
var getAll = require('../api/homeapi');
router.get('/product', (req,res,next) => {
res.json(getAll.all());
});
Upvotes: 0
Views: 35
Reputation: 12953
NodeJS works asynchronously, which means when you call res.json(getAll.all());
the res.json is executed before the query execution ends.
The correct way to do it is:
1. your getAll function should get a callback from outside (just like the mysql function does)
2. the router function should pass a callback to the getAll and in it pass the result to the response
getAll.all = (callback) => {
var userGetSql = 'SELECT * FROM product';
mysql.query(userGetSql, callback);
}
router.get('/product', (req,res,next) => {
getAll.all((result, err) => {
if (err) {
return res.json('some error message');
}
return res.json(result);
});
});
Upvotes: 1