0

I am new for Node, expres, etc..I want to when client entered a contact page, before I loading the page I would like to take the information from the database and transfer the contact page in JSON format.

It is a my following code:

app.get('/contact', function(req, res){
  var array = [];
  console.log('start');
  db.serialize(function () {
    db.each('SELECT * FROM USERS', function (err, row) {
      array.push(row);
      console.log(array.length + ' ' + JSON.stringify(row));
    });
  db.close();

  console.log('array is');
  console.log(array);
  res.render('contact', {array});
  console.log('stop');
  });
});

But my log looks like:

  • start
  • my array is
  • []
  • stop

And now begins to get the information from the database. What i am doing wrong?

Tazo leladze
  • 1,430
  • 1
  • 16
  • 27

1 Answers1

0

You need to close the serialize block before db.close(). Currently, it looks like it is closing after console.log('stop');

Edited: db.serialize() serializes the DB statements of its block, but db.each callbacks are might not be tracked here. So you might use certain wait/synchronization means here. So maybe synchronous-database-queries-with-node-js might help.

Andre Albert
  • 1,386
  • 8
  • 17