Search code examples
node.jssqlitenode-sqlite3

Trouble with callback in nodejs interface to SQLite3


So basically a callback should be run after my SQL command finishes, but for some reason the callback is never executed.

This is the code I currently have:

create : function() {
    var hit = false;
    this.db.serialize(function() {
        this.run("CREATE TABLE if not exists messages (phone_from CHAR(20) NOT NULL, phone_to CHAR(20) NOT NULL, message TEXT)");
        this.run("CREATE TABLE if not exists forwarding (phone_1 CHAR(20) NOT NULL, phone_2 CHAR(20) NOT NULL, phone_bind CHAR(20) NOT NULL)");

        this.get("SELECT * FROM FORWARDING;", function(err, row) {
            hit = true; //<--- Why is this never being hit?
        });

    });
    if (hit) {
        this.insert_forwarding("+18001231234","+18003214321","+18005432322");
        console.log("Inserted initial forwarding address");
    }

}

For some reason the commands each, get, all don't work when it comes to running the SELECT * FROM FORWARDING SQL command.

What am I doing wrong? What don't I understand?

Thank you!


Solution

  • You are assigning hit = true inside a callback function yet you are checking if hit == true synchronously. The callback will execute after your if statement, so that condition will never be true.

    Can you try this?

    create : function() {
        var hit = false;
        this.db.serialize(function() {
            this.run("CREATE TABLE if not exists messages (phone_from CHAR(20) NOT NULL, phone_to CHAR(20) NOT NULL, message TEXT)");
            this.run("CREATE TABLE if not exists forwarding (phone_1 CHAR(20) NOT NULL, phone_2 CHAR(20) NOT NULL, phone_bind CHAR(20) NOT NULL)");
    
            this.get("SELECT * FROM FORWARDING;", function(err, row) {
                if (err) { // throw error }
                else {
                  hit = true; // I guess you don't even need this flag
                  if (hit) {
                    this.insert_forwarding("+18001231234","+18003214321","+18005432322");
                    console.log("Inserted initial forwarding address");
                  }
                }
            });
        });
    }
    

    PS: I would definitely use something like bluebird or native ES6 Promises to move away from the callback pattern and promisify the sqlite library you are using. It will make things much easier to comprehend and you won't end up with nested callbacks resulting in what people like to call "callback hell".