【问题标题】:Trouble with callback in nodejs interface to SQLite3SQLite3的nodejs接口中的回调问题
【发布时间】:2017-02-04 17:13:22
【问题描述】:

所以基本上应该在我的 SQL 命令完成后运行回调,但由于某种原因,回调永远不会执行。

这是我目前拥有的代码:

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");
    }

}

由于某种原因,each, get, all 命令在运行SELECT * FROM FORWARDING SQL 命令时不起作用。

我做错了什么?什么不明白?

谢谢!

【问题讨论】:

    标签: node.js sqlite node-sqlite3


    【解决方案1】:

    您在回调函数中分配hit = true,但您正在检查hit == true 是否同步。回调将在您的 if 语句之后执行,因此该条件永远不会是 true

    你可以试试这个吗?

    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:我肯定会使用 bluebird 或原生 ES6 Promises 之类的东西来摆脱回调模式和 promisify 您正在使用的 sqlite 库。这将使事情更容易理解,并且您不会以嵌套回调结束,从而导致人们喜欢称之为“回调地狱”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-24
      • 2019-06-08
      • 2016-01-07
      • 1970-01-01
      • 2013-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多