I'm trying to get results from an sqlite3 database and get them to render in a jade template but based on the combination of logs I placed in this code it seems as if the template is rendered while waiting for the db query to finish.
var express = require('express');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('test_dab');
/* GET home page. */
var rowResults;
router.get('/', function(req, res) {
db.get('SELECT ID, first_name, last_name FROM customer WHERE ID = 33', function(err, row){
rowResults = 'Hello, ' + row.first_name + ' ' + row.last_name + '!';
console.log(row);
console.log(rowResults);
});
console.log(rowResults);
res.render('index', { title: 'Express',
whatever: rowResults });
});
console.log('Router found index');
module.exports = router;
Here is the output in the console:
//on browser refresh...
undefined
GET / 304
{ ID: 22, first_name: 'Bo', last_name: 'Jackson' }
Hello, Bo Jackson!
GET /stylesheets/style.css 304
GET /javascripts/main.js 304
How do I keep the page from rendering before the db is finished?
The db.get
method is asynchronous. The way you're doing, render
is being executed before db.get
returns and set the rowResults
variable.
You have to call the render
method inside your db.get
method call:
router.get('/', function(req, res) {
db.get('SELECT ID, first_name, last_name FROM customer WHERE ID = 33', function(err, row){
var rowResults = 'Hello, ' + row.first_name + ' ' + row.last_name + '!';
res.render('index', { title: 'Express',
whatever: rowResults });
});
});