0

This is my getHTML5SQLiteData function code written in JavaScript, which returns a value from my Web SQL Database table:

function getHTML5SQLiteData(_keyName){
    var returnValue = undefined;
    if (_isBrowserSupportSQLite()) {
        try {
            _SQLiteDatabase = openDatabase(DEFAULT_SQLITE_DB_SHORTNAME, DEFAULT_SQLITE_DB_VERSION, DEFAULT_SQLITE_DB_NAME, DEFAULT_SQLITE_DB_SIZE);
            _SQLiteDatabase.transaction(function (tx) {
                tx.executeSql('SELECT * FROM My_Table', [], function (tx, results) {
                    var len = results.rows.length;
                    for (var i = 0; i < len; i++){
                        if (results.rows.item(i).keyName == _keyName) {
                            returnValue = results.rows.item(i).keyValue;
                        }
                    }
                }, function (tx, error){});
            });
        } catch(e){
            console.error("Error: " + e);
            return returnValue;
        }
    }
    else {
        // do nothing
    }
    console.log("HTML5 SQLite data: " + returnValue);
    return returnValue;
}  

The problem with this is when I run this function, this is what was printed out in my console:
HTML5 SQLite data: undefined
(The data was there in the database, I checked it by using Developers Tools > Resources tab > Web SQL)
Bonus, when I debugged it in Chrome Developer Tools, it showed that the console.log command was called before the assignment command (returnValue = results.rows.item(i).keyValue;). So I guess the problem here is with JavaScript asynchronous mechanism, but I haven't known how to solve it yet.
Really hope that you guys could help ! Thanks a lot in advanced !

sonlexqt
  • 6,011
  • 5
  • 42
  • 58
  • Your guess is correct, asynchronicity is the reason for your problems. Conceptually, this is the same thing as processing responses to AJAX calls. See [this question](http://stackoverflow.com/q/14220321/1233508) for possible approaches to that. – DCoder Aug 02 '15 at 13:25
  • You can't return a value from this function because the callback from the transaction is the anonymous function which read it. That means you can interpret the return values only from this function and on. – matan7890 Aug 02 '15 at 13:38
  • Thanks ! So how would I, like ... make the whole program wait for the result of the function came before going on ? – sonlexqt Aug 02 '15 at 14:18

0 Answers0