So I want to query some data from an sql database (specifically sqlite), and to put the results in an array. However it doesn't seem to work and I only get an empty array. here's how I tried to do it:
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
I tried doing things like replacing
boards.push(row);
with
boards[boards.length] = row;
and replacing the entire forEach function with
boards = result;
But none of it worked.
console.log(boards);
... is running before the db returns. Your code will:
boards
boards
You need to log boards
inside your callback