I've got a Node.js server with Express and Jade running. On an HTTP request the server will execute the following function:
function home(req, res) {
res.render("site/index", {recordset: recordset}); //render the Jade template
}
Now I would like to pass in an array to the above recordset variable that I can loop through in Jade to populate a drop-down on my html page. I've retrieved the desired array like so:
function runSQLSelect() {
sql.connect(config.db, function(err) {
var request = new sql.Request();
request.query("select MyColumn FROM MyTable", function(err, recordset) {
console.log(recordset);
});
});
}
What is a proper way to asynchronously run the SQL query and pass the subsequent result into my Jade template?
You will have the res.render in the callback from query.
function runSQLSelect(callback) {
sql.connect(config.db, function(err) {
var request = new sql.Request();
request.query("select MyColumn FROM MyTable", function(err, recordset) {
console.log(recordset);
callback(recordset);
});
});
}
function home(req, res) {
runQSQLSelect( function(result) {
res.render("site/index", {recordset: result}); //render the Jade template
});
}
Note, you may want to have your callback invoked in an async fashion, using setImmediate
, you also might consider having your runSQLSelect callback make use of the standard node practice of accepting two parameters callback(err,data)
.