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?

Richard
  • 2,226
  • 2
  • 19
  • 35
  • 1
    The array is printed before anything has been added to it. You have got to wait for completion. – Dan D. Dec 17 '18 at 21:03

2 Answers2

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)
Richard
  • 2,226
  • 2
  • 19
  • 35
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()
Hedegare
  • 2,037
  • 1
  • 18
  • 22
  • Thanks for the reply. My goal is to call a function that returns an array of ids. How might I accomplish this? – Richard Dec 18 '18 at 02:02