2

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
  • i may be missing something, but it looks like you don't have a console.log statement in your second implementation. did you want to print something specific? ... my mistake i see it now. Commented May 3, 2018 at 23:10

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

6 Comments

I need to pass that array through WebSocket, so I will need to put everything in there?
you can use async/await to get the data and use it where you want
well, I've updated as per to async/await. Now you can use records whenever you want
It gave me this error: (async function(){ ^^^^^^^^ SyntaxError: Unexpected token function at createScript (vm.js:56:10) at Object.runInThisContext (vm.js:97:10) at Module._compile (module.js:542:28) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:393:7) at startup (bootstrap_node.js:150:9)
there may be some syntax issue. try matching it with developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.