I am currently using SQLite3 for my database and interacting with it through NodeJS. I am creating a function that returns two datasets from the table. When I use the db.all function and loop through each row, it seems to access the data just fine. When I attempt to return these datasets in an array, only an empty array of empty datasets is returned.
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./db/ecodata.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the ecosystem database.');
});
// MC
async function EcoMcData(id) {
let sql = `SELECT * FROM ecosystem_stats where id = ?`;
let mcData = [];
let date = [];
db.all(sql, [id], (err, rows) => {
if (err) {
throw err;
}
rows.forEach((row) => {
mcData.push(row.market_cap)
date.push(row.time);
});
});
return [date, mcData];
}
async function print() {
let ecod = await EcoMcData("smart-contract-ecosystem");
console.log(ecod);
}
print();
This is what is returned when I run the above code:
[ [], [] ] Connected to the ecosystem database.
However if I was to console log the row data in the row.forEach loop, it is correctly shown in the console.
Is this an asynchronous problem? Are there any solutions to this?