0

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.

Aaron Reese
  • 544
  • 6
  • 18

2 Answers2

0

I found this post which let me to understand how this works Need to keep promise result in a variable for Nodejs mssql validation

and have put my own answer in there. Short version is that in Node you have to set the variable value INSIDE the callback stack rather then returning it from the function to assign to the variable.

fetchDataFromDB('Select top 10 * from X', (err, res)=>{myvar = res})
Aaron Reese
  • 544
  • 6
  • 18
0

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.

You could make the "getCategories" function a middleware that places the result on the request object that can then be obtained by the view. Simply call next() when the operation is complete and then render the view.

app.get('/categories', getCategories, (req, res) => {
    res.render('categories.hbs', {
        pageTitle: 'Catgories',
        currentYear: new Date().getFullYear(),
        categories: req.categories
    });
});
RichCode
  • 21
  • 6