简体   繁体   English

带有JavaScript的SQLite,创建返回行数的函数

[英]SQLite with JavaScript, creating function returning count of rows

i'm trying to create function that returns number of rows in my table in SQLite database using JavaScript with Apache Cordova 2.9.0 API. 我正在尝试使用JavaScript和Apache Cordova 2.9.0 API创建返回SQLite数据库表中行数的函数。 I encountered following problem, callback is executed after function returns something... Here is the code: http://pastebin.com/eFin9yyJ 我遇到以下问题,在函数返回某些内容后执行回调……这是代码: http : //pastebin.com/eFin9yyJ

Alert "global yemp" pops earlier than "temp " + counter 警报“ global yemp”早于“ temp” +计数器弹出

I tried using some timeouts but weird things happened and i stuck 我尝试使用一些超时,但发生了奇怪的事情,我被卡住了

What you probably want, is to take a callback function to your function as parameter, which is called with the value, when value is ready (DB has returned it). 您可能想要的是将一个回调函数作为参数带到函数中,当值准备就绪(DB返回它)时,将使用该值调用该函数。 Example: 例:

var cb = function(value) {
    alert("Got value: " + value);
}

function getNumberOfRecords(name, callback) {
        var temp = 0;
        db.transaction(querySelect, onError);
        function querySelect(tx) {
            //results.rows.length
            tx.executeSql("SELECT count(*) as counter from "+name, [], function (tx, results) {
                        alert(results.rows.item(0).counter);
                        temp = results.rows.item(0).counter;
                        alert("temp = "+ temp);
                        callback(temp);
                    },
                    function (error) {
                        console.log("Cannot read dat data!" + error.message + " z " + name);
                    });
        }
}

getNumberOfRecords("as", cb);

In the example, we first declare function called cb, which takes one parameter (the value which is fetch from database). 在示例中,我们首先声明一个名为cb的函数,该函数接受一个参数(该值是从数据库中获取的)。 It is passed as argument to getNumberOfRecords, which again connects to database and gives the database a callback function, which is in your code anonymous function: 它作为参数传递给getNumberOfRecords,后者再次连接到数据库并为数据库提供回调函数,该函数在您的代码匿名函数中:

function (tx, results)

Database calls this function, when the data is found and then you call the initial cb function, which was given as parameter callback for the upper function, inside it with the value gotten from the database. 找到数据后,数据库将调用此函数,然后调用初始cb函数(该函数作为上层函数的参数回调函数提供),并在其中包含从数据库中获取的值。

If you aren't that familiar with callbacks and asynchronous programming, please let me know so I can improve my answer to be more understandable. 如果您不太熟悉回调和异步编程,请告诉我,以便我将答案改进为更易于理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM