0

I am using the following code

var Year12=new Array();

GetYear(function(Year12) 
{
alert(Year12);
});

   function GetYear(callback) 
     {

       var selectAllStatement = "SELECT DISTINCT year FROM mytable";
       var db = openDatabase("Postit", "1.0", "Notebook", 200000);
       var dataset;
       alert("1");
       db.transaction(function(tx) {
       alert("2");

           tx.executeSql(selectAllStatement, [], function(tx, result) 
           {
           alert("3");
          dataset = result.rows;

          for (var i = 0, item = null; i < dataset.length; i++)
           {

                 item = dataset.item(i);
                 Year12[i]=item['year'];

           }
          callback(Year12);
       });
     });
    }

Here the tx.executeSql statements are not getting executed means alert 3 is not displaying.Is there any way to do this

my name is xyz
  • 329
  • 3
  • 7
  • 17

1 Answers1

2

The db.transaction and tx.executeSql calls are asynchronous, hence the callback functions. That means that GetYear will finish executing and return before the tx.executeSql callback will populate your Year12 array.

Once you have asynchronous behavior and callbacks, the only sensible solution is, of course, more callbacks. You need a structure more like this:

function GetYear(callback) {
    //...
    db.transaction(function(tx) {
        //...
        tx.executeSql(selectuniqueyearStatement, [], function(tx, result) {
            var Year12 = [ ];
            //... populate the locale Year12 using result.rows
            callback(Year12);
        });
    });
}

and then use it like this:

GetYear(function(year12) {
    // Do whatever you need to do with the year12 array...
});

Basically the same code structure and strategies that you use with AJAX calls.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • hi.. Its not working. when iam calling GetYear(function(year12) { });, db.transaction is not getting executed the code written outside db.transaction is executed – my name is xyz Aug 09 '12 at 08:45
  • @VijeshP: What does the new version look like? You can edit the question to add the new version. – mu is too short Aug 09 '12 at 17:45