简体   繁体   中英

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. I encountered following problem, callback is executed after function returns something... Here is the code: http://pastebin.com/eFin9yyJ

Alert "global yemp" pops earlier than "temp " + counter

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). 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). 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:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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