尝试使用节点获取sqlite数据

时间:2014-11-23 19:06:57

标签: javascript jquery node.js sqlite

我在尝试将数据从sqlite数据库中获取到字符串时遇到了一个小问题。这是代码:

router.get('/', function(req, res) {
    var db = req.db;
    var thisShouldWork = 'Hmmm';

    db.all('select rowid as id, value from test', function(err, rows) {
        rows.forEach(function(row){
            console.log(row.id + ": " + row.value);
            thisShouldWork += 'Heeee';
        });
    });
    thisShouldWork += 'What?';
    console.log(thisShouldWork.toString());

    res.send(thisShouldWork);
});

变量'thisShouldWork'只输出'HmmmWhat?'在这段代码的最后,虽然它应该有一些'Heeee'。此外,console.log打印3行数据,因此for循环肯定正在执行。 我没有意识到做错了什么,或者是否有不同/更好的方法来实现同样的目标?

1 个答案:

答案 0 :(得分:1)

回调是异步执行的。

无论你想做什么,都必须在回调结束时移动:

router.get('/', function(req, res) {
    var db = req.db;
    var thisShouldWork = 'Hmmm';

    db.all('select rowid as id, value from test', function(err, rows) {
        rows.forEach(function(row){
            console.log(row.id + ": " + row.value);
            thisShouldWork += 'Heeee';
        });
        thisShouldWork += 'What?';
        console.log(thisShouldWork.toString());

        res.send(thisShouldWork);
    });
});