Search code examples
javascriptjqueryarrayssteroids

Return array to parent function call


I am trying to return an array of objects to a parent function so that I can append them to a div within my HTML.

The function that I have appears to be running an incorrect sequence. Here is my function:

function getRounds() {
    var db = connectDB();
    var items = new Array();
    db.transaction(function(tx) {
        tx.executeSql('SELECT * FROM round', [], function(tx, results) {
            var len = results.rows.length;
            for (var i=0; i<len; i++){
                items.push(results.rows.item(i));
            }
            alert('ONE: '+ JSON.stringify(items));
            return items;
        }, errorCB);
        alert('TWO: '+ items)
    });
    alert('THREE: '+ items);
    return items;
}

What happens is I get an alert of "THREE: ", then "TWO: ", then "ONE: [object]".

Logically it should alert the other way around since the functions are nested, One returns an array of objects which is exactly what I need to be returned to the main function (getRounds).

Any ideas how I can achieve this?

I am using Steroids by Appgyver, the documentation on the Web SQL Database storage can be found here: http://docs.appgyver.com/en/stable/cordova_storage_storage.md.html#SQLResultSetRowList


Solution

  • It's because the call is async! You need to use callbacks!

    function getRounds(callback) {
        var db = connectDB();
        var items = new Array();
        db.transaction(function(tx) {
            tx.executeSql('SELECT * FROM round', [], function(tx, results) {
                var len = results.rows.length;
                for (var i=0; i<len; i++){
                    items.push(results.rows.item(i));
                }
                alert('ONE: '+ JSON.stringify(items));
                callback(items)
            }, errorCB);
        });
    }
    
    getRounds(function(items) {
        console.log(items);
    });