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?
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)