2017-02-03 67 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庫。它會讓事情變得更容易理解,而且不會因嵌套回調而導致人們喜歡稱之爲「回撥地獄」。