Search code examples
javascriptarraysnode.jsobjectarray-push

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.


Solution

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