Sylar
Sylar

Reputation: 12092

Get all data asynchronously using node sqlite3

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.

Upvotes: 1

Views: 1051

Answers (1)

Ivan Vasiljevic
Ivan Vasiljevic

Reputation: 5718

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

Upvotes: 1

Related Questions