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?

4

2 回答 2

1

db.each通过使用 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)
于 2019-01-08T20:49:47.397 回答
0

您在db.each函数完成之前返回数组。这就是为什么它返回一个空数组。

要完成所需的结果,您需要传递一个在所有行都被拉出时回调的函数。

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

ids()
于 2018-12-17T21:28:39.750 回答