2

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?

1 Answer 1

1

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

1 Comment

Hey Felix, thanks a lot! That's exactly what I wanted to know.

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.