0

I'm trying to use sqlite3 in a project and I'm running into a problem. My functions aren't returning any values. I added a console.log before the return statement and oddly enough, it works, but logs after the function has returned.

console.log(getNext());

function establishConnection(callback) {
    const db = new sqlite3.Database('database.db');
    db.serialize(() => {
        callback(db);
    });
    db.close();
}

function getNext() {
    establishConnection(db => {
        db.get('SELECT col1, col2 FROM table ORDER BY priority LIMIT 1;', (err, row) => {
            console.log([row.col1, row.col2]); // works
            return [row.col1, row.col2];       // doesn't work
        });
    });
}

I'm no expert at Node but this seems like something that should work and I don't understand why it doesn't. Could someone please explain this to me and possibly provide a solution?

1 Answer 1

1

getNext is asynchronous, this is why you see logging after the function "returns". Your code currently uses callback style so this answer will follow your format. Using promises or async/await is a more modern approach.

getNext(result => console.log(result));

function establishConnection(callback) {
    const db = new sqlite3.Database('database.db');
    db.serialize(() => {
        callback(db);
    });
    db.close();
}

function getNext(callback) {
    establishConnection(db => {
        db.get('SELECT col1, col2 FROM table ORDER BY priority LIMIT 1;', (err, row) => {
            callback([row.col1, row.col2]);
        });
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.