Async await sqlite in javascript Async await sqlite in javascript sqlite sqlite

Async await sqlite in javascript


I sort of tried sqlite npm package, which implements async/await over splite3, but it is not that easy to use.

A simple way is to create a little module and promessify the main sqlite3 functions.

Here is my simple module I created for a Discord chatbot database:

const sqlite3 = require('sqlite3');const util    = require('util');let db = new sqlite3.Database('./db/chatbot.sqlite3', sqlite3.OPEN_READWRITE, (err) => {    if (err) {        console.error(err.message);    }    console.log('Connected to the chatbot database.');});db.run = util.promisify(db.run);db.get = util.promisify(db.get);db.all = util.promisify(db.all);// empty all data from dbdb.clean_db = async function() {  await db.run("delete from users");  await db.run("delete from members");  await db.run("delete from guilds");  db.run("vacuum");}// any kind of other function ...// and then export your modulemodule.exports = db;

How to use - now you can use the module like this in your code:

const db = require('./db');// get one userconst myUser = await db.get("select * from users where id = ?", [id]);if (! myUser)    return console.log("User with id", id, "not found");// get all usersconst users = await db.all("select * from users");users.map((user) => { console.log(user.id, "/", user.name); });// ... etc ...


Try the sqlite package, rather than the sqlite3 used in the demo. It has better support for async await.


For me the simplest solution would be to encapsulate the operation in a Promise like so:

const res = await new Promise((resolve, reject) => {    db.each('SELECT id FROM table', [], (err, row) => {        if (err)            reject(err)        resolve(row)    })})console.log(res)

With this you'll have the row result in res outside the callback and synchronously.