所以基本上应该在我的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");
}
}
由于某种原因,在运行SELECT * FROM FORWARDING
SQL命令时,命令each, get, all
不起作用。
我做错了什么?我有什么不明白的?
谢谢!
您正在回调函数中分配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 Promise 的东西来摆脱回调模式并promisify
您正在使用的 sqlite 库。这将使事情更容易理解,并且您最终不会得到嵌套回调,从而导致人们喜欢称之为"回调地狱"。