0
我需要您的帮助来创建一个允许发送查询并返回结果的SQLite类。Javascript函数不返回查询结果(SQLitePlugin for Cordova)
我知道事务/ executionql是异步的,我试图解决这个问题。
我写了这个代码:
function SQLite(pName){
this.result = null;
//External function
this.Query = function(pQueryStr) {
this.result = null;
execQuery(pQueryStr);
//Waiting query result. While is null, sleep...
while(this.result == null){null;} //This line doesn't work
return this.result;
}
//Internal function for execute query
function execQuery(pQueryStr) {
//Emulating transacion-executesql functions with lag
setTimeout(function(){
this.result = "my query result";
}, 3000);
}
}
db = new SQLite("dbName");
var res = db.Query("query request string");
//As I can't wait for SQL result, 'res' returns null.
alert("External result: " + res);
这并不工作,但评论“而”行......这个作品将此代码添加到结束。
setTimeout(function(){
alert("External result (with lag): " + this.result);
}, 5000);
我的问题:我需要'虽然'。这使得函数等待查询结果被报告。
任何解决方案或解决方法?
谢谢你的时间!
我认为主要问题是Javascript中的单线程属性。我的应用程序不能工作,因为execQuery在'while'完成之前无法启动执行。我正在寻找一个单一功能的解决方案,但我怀疑这是不可能的,因为我需要两个功能。 – DaleAlEnter 2014-10-18 07:58:23
你说得对。这就是为什么我建议使用承诺或回调。代替while循环,您可以使递归setTimeout不阻止应用程序 – n0mercy 2014-10-18 12:50:02
添加递归检查而不是while循环的示例 – n0mercy 2014-10-18 12:56:51