Javascript 函数不返回查询结果(SQLitePlugin for Cordova)



我需要您的帮助来创建一个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函数等待查询结果的报告。

有什么解决方案或变通方法吗?

谢谢你抽出时间!

我建议使用回调或promise,后者是我更喜欢的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)

最新更新