无法在Node.js上使用sqlite3将行放入数组中 [英] Can't put rows into array using sqlite3 on Node.js
问题描述
我在Node.js中有一个代码,可以从SQLite数据库中选择所有内容并打印每一行,并且它行得通,这是代码:
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...');
});
它打印:
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);
}
它打印:
Connected...
Database closed...
解决方案:修改代码以使其与 async/await
一起使用并将Node更新到版本8.11.1后,它可以工作,代码:
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();
推荐答案
这是因为 db.all
是异步
.数据数组尚未填充,您正在尝试遍历它.只需将 for
循环移到内部,就可以完成.
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.
您的最终代码应为
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.使用 for(.. in ..)
不是一个好主意,最好使用 forEach
ps. It is not good idea to use for(..in..)
you better use forEach
这篇关于无法在Node.js上使用sqlite3将行放入数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!