This is an Express site.
Here is how I had my code. This is just some spiked code for me to play with to try to get something dirty working:
index/routes.js
router.get('/', function(req, res) {
var sqlStatement = "Select top 10 from customers";
var rows = connection.invokeQuery(sqlStatement);
res.render('index', { title: 'My App', customers: rows});
});
module.exports = router;
The problem is it's not waiting for the query to complete before trying to render the data to the page. So I tried putting it in a callback, but still doesn't work. Do I need a promise or watcher or something?
router.get('/', function(req, res) {
var sqlStatement = "Select top 10 from customers";
var rows = connection.invokeQuery(sqlStatement, function(){
res.render('index', { title: 'My App', customers: rows});
});
});
I created this method also:
connection.invokeQuery = function(sqlQuery){
...code before this
db.query(sqlQuery, function(err, rows){
if(rows ) {
data = rows;
console.log(rows);
}
if(err) { console.log(err); }
})
}
);
});
return data;
};
Another thing I noticed is that in my invokeQuery function when I fire up my site, it's hitting the return data
right off the bat. It doesn't even hit my sql query yet. So that's another problem.
I'm probably going about this completely wrong but I don't get how to handle this probably very common scenario.
ANSWER
Ok this is easy, figured it out.
var rows = connection.invokeQuery(sqlStatement, function(rows){
res.render('index', { title: 'Dave\'s App', cobrands: rows});
});
connection.invokeQuery = function(sqlQuery, callback){
...code before this
db.query(sqlQuery, function(err, rows){
if(rows ) {
data = rows;
console.log(rows);
callback(rows);
}
if(err) { console.log(err); }
})
}
);
});