lundi 29 juin 2015

Fixing async error in Node + Sqllite3

I have the following code :

// reference the http module so we can create a webserver
var http = require("http");
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('movies.db');

// create a server
http.createServer(function(req, res) 
{
    var catloc = req.url.indexOf("category");
    if (catloc > 0)
    {
        // part 1
        var page = csm1;
        var url_parts = url.parse(req.url, true);
        var query = url_parts.query;
        var category = query.type;

        // part 2
        db.each("SELECT * FROM MOVIES WHERE LOWER(CATEGORY1)='"+category+"'", function(err, row)
        {
            if (err) throw err;
            page += row.html;
        });

        // part 3
        page += csm3;
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(page);
    }
}).listen(process.env.PORT, process.env.IP);

part1 should be executed, followed by part2, then part3. But part1+part3 is executed before part2 due to async.
I would like help on how I could set up a callback to fix this.

Any help is appreciated!

Aucun commentaire:

Enregistrer un commentaire