wingshauser wingshauser - 3 months ago 12
Javascript Question

Trying to understand how to incorporate a callback into Node.js/SQLITE

I'm pretty new to all this and am struggling to figure out how to control the order of operations in my node code. When I load the page, my variables say 'undefined' until I refresh the browser a second time. I am assuming this is because the Jade/Pug page is being rendered before the db query. Everything I have read suggests that I need to control the order using callbacks, but I can't seem to get it working. This is my pre-butchered code.

exports.count = function(req, res) {

//Get in count
db.all("SELECT COUNT(id) as cnt FROM tableName WHERE status='in'",
function(err, rows){
inCount=rows[0].cnt;
console.log("Items In: " + inCount);
});

//Get out count
db.all("SELECT COUNT(id) as cnt FROM tableName WHERE status='out'",
function(err, rows){
outCount=rows[0].cnt;
console.log("Items Out: " + outCount);
});

//Render Count to Pug view
res.render('count', { _incount: inCount + ' in', _outcount: outCount + ' out'});

};


This is what I was trying to follow, but it causes my page to time out.
node.js and express passing sqlite data to one of my views

Any help would be most appreciated, Thanks!!

Answer

A module for managing asynchronous control flow - like async - can help you with this. If you need an introduction to async, there is a blog post here that you might find useful.

For example:

exports.count = function(req, res) {

  async.series([
    function (callback) {

      //Get in count
      db.get("SELECT COUNT(id) as cnt FROM tableName WHERE status='in'", callback);
    },
    function (callback) {

      //Get out count
      db.get("SELECT COUNT(id) as cnt FROM tableName WHERE status='out'", callback);
    }
  ], function (error, results) {

    if (error) {
      // ... handle the error in an appropriate manner
    } else {
      res.render('count', { _incount: results[0].cnt + ' in', _outcount: results[1].cnt + ' out'});
    }
  }
};

Also, get would be more appropriate for the queries that you are making in your example, as there will only be a single row in each result.

Comments