修复Node + Sqllite3中的异步错误

时间:2015-06-30 04:48:07

标签: node.js sqlite

我有以下代码:

// 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,然后执行part2,然后执行part3。但是由于异步,part1 + part3在part2之前执行 我想帮助我如何设置一个回调来解决这个问题。

感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

使用db.each的{​​{3}}回调:

    // 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;
    },function(err,total){
       // part 3
       page += csm3;
       res.writeHead(200, {'Content-Type': 'text/html'});
       res.end(page);
    });