无法将 sql 行添加到节点 js 中的 javascript 数组

Can't add sql rows to a javascript array in node js

所以我想从 sql 数据库(特别是 sqlite)中查询一些数据,并将结果放在一个数组中。但是它似乎不起作用,我只得到一个空数组。以下是我的尝试:

var boards = []; // init the boards array
const sqlite = require('sqlite3').verbose(); // init sqlite
var db = new sqlite.Database("database.db"); // init the database

// the query
db.all(`select * from boards;`,(err, result) => {
    // error handling
    if (err) throw err;
    // loop threw all the results and add them to the boards array
    result.forEach((row) => {
        boards.push(row);
    });
});
console.log(boards);
// outputs [], even if there's something in the boards table

我尝试做一些事情,比如替换

        boards.push(row);

        boards[boards.length] = row;

并将整个 forEach 函数替换为

    boards = result;

但是 none 有效。

console.log(boards);

... 在数据库 returns 之前是 运行。您的代码将:

  1. 发送数据库调用
  2. 日志boards
  3. (当数据库调用 returns 时):向 boards
  4. 添加行

您需要在回调中记录 boards