Ben
Ben

Reputation: 301

Web SQL transaction returns empty

This works when I use the success callback to write directly to the DOM. But I would like to seperate data from display and just a return and array. Everything I've tried returns and empty array. Any thoughts? Do I need to use a closure of some sort?

function getExercises(){
    var result = []

    db.transaction(function(tx) {
            tx.executeSql('SELECT id, title, weight, reps FROM exercises', [],function(tx, rs) {
                for(var i=0; i<rs.rows.length; i++) {
                    var row = rs.rows.item(i)
                    result[i] = {
                        id: row['id'],
                        title: row['title'],
                        weight: row['weight'],
                        reps: row['reps']
                    }

                }

            })
        })
    return result;

};

Upvotes: 0

Views: 1890

Answers (1)

Matthew
Matthew

Reputation: 15992

The transaction is performed asynchronously so you need to do something with the result from the success callback. For example:

..
tx.executeSql('SELECT id, title, weight, reps FROM exercises', [],function(tx, rs) {
      var result = [];
      for(var i=0; i<rs.rows.length; i++) {
          var row = rs.rows.item(i)
          result[i] = {
                    id: row['id'],
                    title: row['title'],
                    weight: row['weight'],
                    reps: row['reps']
         }
      }
      console.log(result);
});
..

Will log the result to your console.

In the code you posted in your question, none of the callbacks are executed before execution reaches the return result statement - i.e. the array would not have been populated yet - because executeSql is asynchronous: it doesn't block while it executes and just executes the error or success callback when it's done.

Upvotes: 1

Related Questions