1

I have a very simple Express route which queries a database and sends the results to a templating engine (handlebars).

var express = require('express');
var router  = express.Router();
var db      = require('./../db');



/* GET home page. */
router.get('/', (req, res, next) => {

    // get db connection
    db.connection.connect((error) => {
        if (error) throw error;
      });

    var query = `SELECT
                    S.store_id, S.name, S.city, S.state
                FROM Store S`;

    db.connection.query(query, (error, results, fields) => {
        if (error) throw error;
        res.render('addPurchase', {storeData: results});

    });

});

module.exports = router;

As written, this works because my callback from the query execution is the res.render, meaning nothing will be rendered until I get my query results. Fine.

What I want to do is encapsulate my database query in its own function. So,

router.get('/', (req, res, next) => {

    // CALL NEW FUNCTION HERE
    var queryResults = getStoreData();
    res.render('addPurchase', {storeData: queryResults});
});

module.exports = router;


function getStoreData() {

    db.connection.connect((error) => {
        if (error) throw error;
      });


    var query = `SELECT
                    S.store_id, S.name, S.city, S.state
                FROM Store S`;

    db.connection.query(query, (error, results, fields) => {
        if (error) throw error;
        return JSON.stringify(results);
    });

}

But now, my res.render no longer waits for the query to complete, meaning my rendered HTML does not contain the query results.
How can I have the res.render wait on the results from the query? I think the answer might contain promises/async, but I'm not sure how things should be set up.

Thanks!

Eric
  • 11
  • 1

0 Answers0