0

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.

3

2 Answers 2

2

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(); 

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

Comments

1

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;

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.