2

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

1 Answer 1

10

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

I feel rather daft. Thanks a lot!
@Karl -- Always happy to help - once you can wrap your head around callbacks everything becomes to much easier to understand :)
I'm not a Javascript wiz, so it's definitely a learning curve and will help me so much with this project. Really appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.