Get all data asynchronously using node sqlite3

吃可爱长大的小学妹 提交于 2021-02-11 02:25:08

问题


I need to get all data using db.all() asynchronously. I do not want to run other functionality/code within the call back. I would like to "export" the results. Is that ok?

* Im new to SQLite 😬 *

const sqlite3 = require('sqlite3').verbose()
const db = new sqlite3.Database('./db/subscribers.db')

const createSQLStatement = `CREATE TABLE IF NOT EXISTS subscriptions (id INTEGER PRIMARY KEY AUTOINCREMENT, subscriber TEXT)`
db.run(createSQLStatement)

exports.getAllSubscribers = async () => {
  const $sql = `SELECT * FROM subscriptions`
  return await db.all($sql, (err, rows) => {
    if (err) {
      return
    }

    // I wish to export "rows" which is an array
    return rows
  })
}

In another file

const { getAllSubscribers } = require('./foo')

getAllSubscribers().then(subs => {

  // subs is not what I expect it to be.
  // I'm getting:
  // Database { open: true, filename: './db/subscribers.db', mode: 65542 }
  // But I do need subs here to loop over and not inside of getAllSubscribers()

})
.catch(e => console.log(e))

I've also looked on this doc but nothing seems to give me the result I'd expect.


回答1:


When you are using then and catch you don't use await.

So you need to improve your first script:

const sqlite3 = require('sqlite3').verbose()
const db = new sqlite3.Database('./db/subscribers.db')

const createSQLStatement = `CREATE TABLE IF NOT EXISTS subscriptions (id INTEGER PRIMARY KEY AUTOINCREMENT, subscriber TEXT)`
db.run(createSQLStatement)

exports.getAllSubscribers = () => {
  const $sql = `SELECT * FROM subscriptions`
  return db.all($sql, []);
}

In another file you can use await like this:

const { getAllSubscribers } = require('./foo')
const getSubscribers = async () => {
    const subscribers = await getAllSubscribers();
};

You can find more example here: https://www.scriptol.com/sql/sqlite-async-await.php



来源:https://stackoverflow.com/questions/55143166/get-all-data-asynchronously-using-node-sqlite3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!