node.jssqlitepromiseasync-await

Async-Await Still running asynchronously


Awaiting Select * function then doing stuff after its done printing. But its rushing right past the await doing everything after then printing the output. so its sort of going: calls Await function then other stuff after await runs before resolve is called then prints out await function.

I honestly have tried alot. making anonymous async block to run the awaits inside a function. i wasn't using promises for functions before but then added them thinking i needed to resolve them. but no dice.

var sqlite3 = require('sqlite3').verbose();

var db = new sqlite3.Database(__dirname+'/requestLog.db');

test();
async function test(){
    await selectAll();

    console.log('test')
}

function selectAll(){
    return new Promise((resolve, reject) => {
        try {
            db.serialize(function() {   
                db.each("SELECT rowid AS id,* FROM requests", function(err, row) {
                    console.log(row);  
                });
                resolve()
            });
        } catch (error) {
            console.log(`Error With Select ALL(): \r\n ${error}`)
            reject();
        }
    });
 }

Im sure its just me missing something ridiculous. and now i feel like im going down a rabit hole and going around in circles please dont judge me lol

I wanted to print everything in the database to the console. And then do the ("test")or anything after i print it.

but everything runs right through the await


Solution

  • The problem is the resolve() being called after db.each(), the right place to put the resolve would be the complete callback: Database#each(sql, [param, ...], [callback], [complete]), from the docs. https://github.com/TryGhost/node-sqlite3/wiki/API#eachsql--param---callback--complete

    function selectAll() {
        return new Promise((resolve, reject) => {
            try {
                db.serialize(function () {
                    db.each("SELECT rowid AS id,* FROM requests", function (err, row) {
                        console.log(row);
                    },
                        (err, rowCount) => {
                            if (err) reject(err);
                            resolve(rowCount);
                        }
                    );
                });
            } catch (error) {
                console.log(`Error With Select ALL(): \r\n ${error}`)
                reject();
            }
        });
    }