Adarsh Nair
Adarsh Nair

Reputation: 390

Getting variable outside of query block in Nodejs with sqlLite

I want to store all the rows from table to array(arr), I need to get the stored array outside of the defined query section. Is there a way I can get all the rows outside db.each such that I can manipulate them further.

var arr=[];
db.each("SELECT * FROM login", function(err, row) {
    var title=row.title;
    var context=row.context;
    var newItem = {
        'user': user,
        'pwd': pwd
    };
    arr.push(newItem);
});     
console.log(arr); //Outputs []

Upvotes: 0

Views: 1265

Answers (1)

jshawl
jshawl

Reputation: 3483

Because db.each is an asynchronous function, you need to use another function as a callback, like:

var arr=[];
db.each("SELECT * FROM login", function(err, row) {
    var title=row.title;
    var context=row.context;
    var newItem = {
        'user': user,
        'pwd': pwd
    };
    arr.push(newItem);
}, function(){
  console.log(arr)
});     

Reference: https://github.com/mapbox/node-sqlite3/wiki/API#databaseeachsql-param--callback-complete

Upvotes: 2

Related Questions