I have a code in Node.js that selects everything from a SQLite Database and print every row and it works, here's the code:
var sqlite3=require('sqlite3').verbose();
var db=new sqlite3.Database('./database.db',(err)=>{
if(err){
return console.error(err.message);
}
console.log('Connected...');
});
db.all('SELECT * FROM langs ORDER BY name',[],(err,rows)=>{
if(err){
return console.error(err.message);
}
rows.forEach((row)=>{
console.log(row.name);
});
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Database closed...');
});
It prints:
Connected...
C
Java
Database closed...
But when I try using this to get the rows into an array, it doesnt work:
var data=[];
db.all('SELECT * FROM langs ORDER BY name',[],(err,rows)=>{
if(err){
return console.error(err.message);
}
rows.forEach((row)=>{
data.push(row);
});
});
for(col in data){
console.log(col.name);
}
It prints:
Connected...
Database closed...
SOLUTION: After modifying the code to work with async/await and updating Node to version 8.11.1, it works, code:
var data=[],records=[];
function getRecords(){
return new Promise(resolve=>{
db.all('SELECT * FROM langs ORDER BY name',[],(err,rows)=>{
if(err){
return console.error(err.message);
}
rows.forEach((row)=>{
data.push(row);
});
resolve(data);
});
});
}
async function asyncCall(){
records=await getRecords();
records.forEach(e=>{
console.log(e.name);
});
}
asyncCall();
console.logstatement in your second implementation. did you want to print something specific? ... my mistake i see it now.