2017-02-03 68 views
0

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

这是我目前拥有的代码:

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("+180","+18003214321","+18005432322"); 
     console.log("Inserted initial forwarding address"); 
    } 

} 

出于某种原因,命令each, get, all当谈到运行SELECT * FROM FORWARDING SQL命令不起作用。

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

谢谢!

回答

0

您在回调函数中指定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("+180","+18003214321","+18005432322"); 
       console.log("Inserted initial forwarding address"); 
       } 
      } 
     }); 
    }); 
} 

PS:我肯定会使用类似bluebird或本地ES6有望摆脱回调格局路程,promisify您正在使用的SQLite库。它会让事情变得更容易理解,而且不会因嵌套回调而导致人们喜欢称之为“回拨地狱”。