Been going round in circles for 2 days now. I am getting some data from Azure SQL database (connection parameters are in sqlconfig)
function getCategories(callback) {
var conn = new mssql.ConnectionPool(sqlconfig);
var req = new mssql.Request(conn);
console.log('in getCategories');
conn.connect((err) => {
if (err) {
console.log('Connection Error:', err);
}
req.query("Select top 3 * from Categories", (err, rs) => {
if (err) {
console.log('Select error: ', err);
} else {
callback(rs.recordsets[0]);
}
conn.close();
});
})
}
I know the data is being returned correctly because when I do
getCategories((rs) => console.log('Get-Categories', rs));
I get the expected results
I am struggling to get the dataset to pass through to the view
app.get('/categories', (req, res) => {
res.render('categories.hbs', {
pageTitle: 'Catgories',
currentYear: new Date().getFullYear(),
categories: getCategories((rs) => rs)
});
});
returns nothing in the categories as it is undefined - so the callback has not finished running when the code is called.
How do I make the app.get wait until the getCategories has completed so that the data is ready to pass back to the view.