Schoerlock
Schoerlock

Reputation: 23

asynchronous callback within a object method for javascript database operations

I would like to encapsulate SQLite database commands in a 'DBManager' class. To read the data, I've written the following lines:

DBManager.prototype.readMyData = function(param1, param2) {
this.db.transaction(function(tx) {
    tx.executeSql("SELECT * FROM myTable WHERE param1 <= ?",
    [param1],
    function(tx, result) {
      var myData = [];
      for (var i=0; i<result.rows.length; i++) {
                var row = result.rows.item(i);
                myData.push(row);
              }
    },
    errorHandler);
});
    return myData;

}

The Problem: If I call the method readMyData() the return command is executed before the transaction method and its inner stuff.

How can I handle it so that the return value of readMyData() isn't empty but holds the myData array?

Upvotes: 2

Views: 571

Answers (1)

Felix Kling
Felix Kling

Reputation: 816600

You can't, you have to provide a callback to readMyData:

DBManager.prototype.readMyData = function(param1, param2, callback) {
    this.db.transaction(function(tx) {
        tx.executeSql("SELECT * FROM myTable WHERE param1 <= ?", [param1],
            function(tx, result) {
                var myData = [];
                for (var i=0; i<result.rows.length; i++) {
                    var row = result.rows.item(i);
                    myData.push(row);
                }
                callback(myData);  // <- passing the data to the callback
            },
            errorHandler);
    });
}

and then call it with:

db.readMyData(foo, bar, function(result) {
   // work with result here
});

Upvotes: 1

Related Questions