0

I'm using node to read from a table in SQLite and render to a webpage, but I can't seem to pass the values retrieved from the table on the server to client. I am able to log the values stored as JSON to the console, but having no luck passing them through. Here is my code:

//Set up web server
const express = require('express')
const app = express()

//Set view engine and allow access to public/css
app.set('view engine', 'ejs')
app.use(express.static('public'));

//Start server
app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

//Process get request and point to index.ejs
app.get('/', function(req, res) {

    res.render('index', { 
        temps: getTemps()
    });
});

function getTemps(){

    var sqlite3 = require('sqlite3').verbose();
    var db = new sqlite3.Database('fishtank.db');

    var temps = "";

    db.serialize(function() {
        var rowset = db.each("SELECT id, datetime, temp FROM watertemp", function(err, row) {

            temps = [{
                id: row.id,
                datetime: row.datetime,
                temp: row.temp
            }];

            console.log(temps);
            return temps;

        });
    });

    //Close databse connection
    db.close();
}
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Patrick Hund Feb 27 '18 at 07:39
  • If you take a close look at the getTemps function, you'll see that it doesn't actually return anything. The callback that you provide to db.serialize does, sure, but that's an asynchronous call and doesn't help. This is a very common mistake, so I've marked it as a duplicate. If you follow the link to the duplicate, it should help you on your way to learn about synchronous programming in Node.js – Patrick Hund Feb 27 '18 at 07:41
  • Great, thanks. That was a really helpful article! – Adam Eldridge Mar 19 '18 at 21:40

0 Answers0