0

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 []
2
  • Typical case for a promise! Commented Jul 25, 2015 at 15:00
  • I need to prepare JSON from database Commented Jul 25, 2015 at 15:01

1 Answer 1

2

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

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

1 Comment

Thanks for this quick reply.

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.