Reputation: 314
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();
Upvotes: 2
Views: 3163
Reputation: 10148
This is because db.all
is asynchronous
. Data array is not yet populated and you are trying to loop through it. Just move for
loop inside and you're done.
Your final code should look like
var data=[],
records = [];
function getRecords(){
return new Promise((resolve,reject)=>{
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(){
records = await getRecords();
})()
ps. It is not good idea to use for(..in..)
you better use forEach
Upvotes: 3