2

I want to build an array of ids from a sqlite query using the node-sqlite3 library.

const sqlite3 = require('sqlite3')
const db = new sqlite3.Database('./db/database-name.db')

let ids = () => {
  let sql = `select id from users;`
  let result = []
  db.each(sql, (err, row) => {
    // console.log(row.id)
    result.push(row.id)
  })
  return result
}

console.log(ids())

The console.log() statement prints an empty array. What am I doing wrong?

1
  • 1
    The array is printed before anything has been added to it. You have got to wait for completion. Commented Dec 17, 2018 at 21:03

2 Answers 2

1

I was able to achieve the desired result by wrapping the call to db.each with a Promise:

const selectIds = () => {
  return new Promise((resolve, reject) => {
    let result = []
    db.each(`select id from users;`, (err, row) => {
      if(err) { reject(err) }
      result.push(row.id)
    }, () => {
      resolve(result)
    })
  })
}

selectIds().then((ids) => console.log(ids)
Sign up to request clarification or add additional context in comments.

Comments

0

You are returning the array before the db.each function finishes. That's why it returns an empty array.

To accomplish the desired result you need to pass a function thats called back when all rows have been pulled.

let ids = () => {
  let sql = `select id from users;`
  let result = []
  db.each(sql, (err, row) => {
    result.push(row.id)
  }, () => {
    console.log(result)
  })
}

ids()

1 Comment

Thanks for the reply. My goal is to call a function that returns an array of ids. How might I accomplish this?

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.