my name is xyz
my name is xyz

Reputation: 349

Accessing variable inside WebSQL Function

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

Upvotes: 0

Views: 509

Answers (1)

mu is too short
mu is too short

Reputation: 434585

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.

Upvotes: 2

Related Questions