2017-02-03 19 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"); 
    } 

} 

SELECT * FROM FORWARDING SQL 명령을 실행에 관해서 명령 each, get, all가 작동하지 않는 몇 가지 이유 :

내가 현재 가지고있는 코드입니다.

내가 뭘 잘못하고 있니? 내가 이해하지 못하는게 뭐야?

감사합니다.

답변

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가 라이브러리를 이동하는 약속. 이해하기가 훨씬 쉬워지고 중첩 된 콜백으로 끝나지 않아 사람들이 "콜백 지옥"이라고 부르는 것을 만듭니다.