尝试使用 node 获取 sqlite 数据

Trying to get sqlite data using node

本文关键字:获取 sqlite 数据 node      更新时间:2023-09-26

我在尝试将数据从 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"只是在这段代码的末尾输出"嗯什么?",而它也应该有一些"Heeee"。此外,控制台.log打印 3 行数据,因此 for 循环肯定会执行。我是否在没有意识到的情况下做错了什么,或者是否有不同/更好的方法来实现同样的事情?

回调以异步方式执行。

之后要执行的任何操作都必须在回调结束时移动:

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);
    });
});