0

I am new to nodejs and asynchronous language. I am trying to read data from sqlite3 and push them in an array. And at the end print the array. I have pushed the data to the array successfully and I can log them from inside the iteration. But when I attempt to read the array from outside looks like the array is empty.

var express = require('express');
var app = express();

var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('testDb');

app.use(express.static(__dirname + '/public'));

db.serialize(function() {
  var infoCOllection = [];

  db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {

    infoCOllection.push(row.id + ": " + row.info);
  });
        console.log(infoCOllection);
  });

db.close();

app.listen(3000);
console.log('sever is run on port 3000');

I read many of examples and explanations about callback and nodejs but did not understand the structure and its relation with my code. Can anybody help me in the problem with my code. Thanks in advance

2 Answers 2

1

From the docs

Database#each(sql, [param, ...], [callback], [complete])

You can get array after completion of db.each like this

db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
    infoCOllection.push(row.id + ": " + row.info);
}, function(err, rows){ //callback for completion of .each method
      console.log(infoCOllection); //you can have your array printed here
});
Sign up to request clarification or add additional context in comments.

Comments

0

Thanks very much Jyothi for your answer and the link. Now every thing is clear for me. :) I have just tried another way which retrieves all rows as below:

    db.all("SELECT rowid AS id, info FROM lorem",function(err, rows) {
        rows.forEach(function(row) {
            infoCOllection.push(row.id + ": " + row.info);
        });
        console.log(infoCOllection);
  });

Cheers

Comments

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.