Javascript函数没有';t返回查询结果(用于Cordova的SQLitePlugin)

Javascript函数没有';t返回查询结果(用于Cordova的SQLitePlugin),javascript,sqlite,cordova,asynchronous,Javascript,Sqlite,Cordova,Asynchronous,我需要您的帮助来创建一个SQLite类,它允许发送查询并返回结果 我知道transaction/executesql是异步的,我正在尝试解决这个问题 我写了这段代码: function SQLite(pName){ this.result = null; //External function this.Query = function(pQueryStr) { this.result = null; execQuery(pQuerySt

我需要您的帮助来创建一个SQLite类,它允许发送查询并返回结果

我知道transaction/executesql是异步的,我正在尝试解决这个问题

我写了这段代码:

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);
这不起作用,但评论“while”行。。。这可以将此代码添加到末尾

setTimeout(function(){
    alert("External result (with lag): " + this.result);
}, 5000);
我的问题是:我需要“while”。此make函数等待报告查询结果

有什么解决方案或解决办法吗


谢谢你的时间

我建议使用回调或承诺,后者是我更喜欢的开始

如果您仍然坚持使用while(这很糟糕,因为您的应用程序将挂起,直到结果返回)。您的while循环不工作

setTimeout(function(){
        this.result = "my query result";
    }, 3000);
因为此上下文已更改(此处有更多信息:),您必须在外部范围中声明此属性,或者绑定此上下文

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)

我认为主要问题是Javascript中的一个线程属性。我的应用程序无法工作,因为在“while”完成之前,execQuery无法开始执行。我正在寻找一个单功能的解决方案,但我怀疑这是不可能的,因为我需要两个功能。你是对的。这就是为什么我建议使用承诺或回调。代替while循环,您可以使recursive setTimeout不阻塞appadded,这是一个递归检查代替while循环的示例recursive check与“while”有相同的问题。我可以通过回调或事件部分地解决我的问题。我之所以说“部分”,是因为“异步”+“唯一线程”对MVC和OOP设计有影响。无论如何,谢谢你抽出时间。