2014-10-17 101 views
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); 

我的问题:我需要'虽然'。这使得函数等待查询结果被报告。

任何解决方案或解决方法?

谢谢你的时间!

回答

1

我会建议使用回调或承诺后者是我更喜欢https://www.promisejs.org/是一个很好的开始。

如果你仍然坚持使用while(这是坏的,因为你的应用程序将挂起,直到结果回来)。 while循环不起作用

setTimeout(function(){ 
     this.result = "my query result"; 
    }, 3000); 

,因为这种情况下发生了改变(更多关于此这里:http://ryanmorr.com/understanding-scope-and-context-in-javascript/),你要么在外部范围声明此属性,或者绑定此背景下

function execQuery(pQueryStr) { 
    var that = this; 
    //Emulating transacion-executesql functions with lag 
    setTimeout(function(){ 
     that.result = "my query result"; 
    }, 3000); 
} 

您还需要进行递归检查而不是while,例如:

var that = this; 
function checkResult() { 
    if (that.result == null) { 
     console.log('repeat') 
     setTimeout(checkResult,1); 
    } 
    else { 
     console.log('success'); 
    } 
} 
checkResult(); 
setTimeout(function() { that.result = true; },100) 
+0

我认为主要问题是Javascript中的单线程属性。我的应用程序不能工作,因为execQuery在'while'完成之前无法启动执行。我正在寻找一个单一功能的解决方案,但我怀疑这是不可能的,因为我需要两个功能。 – DaleAlEnter 2014-10-18 07:58:23

+0

你说得对。这就是为什么我建议使用承诺或回调。代替while循环,您可以使递归setTimeout不阻止应用程序 – n0mercy 2014-10-18 12:50:02

+0

添加递归检查而不是while循环的示例 – n0mercy 2014-10-18 12:56:51