Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 517
Karl Avatar asked Dec 12 '25 15:12

Karl


1 Answers

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);
});
like image 100
tymeJV Avatar answered Dec 14 '25 05:12

tymeJV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!