esafwan
esafwan

Reputation: 18009

Using push for inserting JS object into an array wont work at certain context

In the below code, users.push used within ‘db.each’ wont work. However, if I move ‘users.push’ outside then it seems to work.

How can I push the new objects from db.each into the users array?

let db = new sqlite3.Database('./db/main.db', (err) => {
  if (err) console.error(err.message);
  console.log('Connected to the main database.');
});

var users = [];

db.serialize(() => {
  db.each(`SELECT email, name FROM users`, (err, row) => {
    if (err) console.error(err.message);
    let user = {
      email: row.email,
      name: row.name
    }
    users.push(user);
  });
});

console.log(JSON.stringify(users));
db.close();

I am using express and sqlite3 node packages.

Upvotes: 0

Views: 102

Answers (2)

antoinechalifour
antoinechalifour

Reputation: 495

It's because db.serializeand db.each are asynchronous functions (and return immediately, thus executing console.log before the db callbacks are executed).

Here should be a working example :

db.serialize(() => {
      db.each(`SELECT email,
                      name
               FROM users`, (err, row) => {
        if (err) {
          console.error(err.message);
        }

        let user = {
            email : row.email,
            name : row.name
        }

        users.push(user);

        console.log(JSON.stringify(users));

        db.close(); 

      });
    });

Upvotes: 2

Nino Filiu
Nino Filiu

Reputation: 18473

First error: asynchronicity not handled properly

As Antoine Chalifour pointed out, you call console.log(JSON.stringify(users)); before users gets modified in the asynchronous callback. Refer to his answer for fix and explanations.

Second error: errors not handled

You wrote if (err) { console.error(err.message); } then go on with the rest of the function. That is bad, because an error might happen and you'd just continue with your program. You should instead write something like:

if (err) {
  console.error(err);
  return;
}

or:

if (err) throw err;

Upvotes: 1

Related Questions