Can't put rows into array using sqlite3 on Node.js

我与影子孤独终老i 提交于 2020-12-12 18:18:58

问题


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();

回答1:


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



来源:https://stackoverflow.com/questions/50164935/cant-put-rows-into-array-using-sqlite3-on-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!