views:

1370

answers:

3

How can I get the following JavaScript to return row so I can access it outside the transaction? All of Apple's example code seems to have HTML written to the browser within the transaction instead of ever passing data back to a calling function.

Along the lines of:

function getData() {
  db.transaction(function(tx) {
    tx.executeSql("SELECT id FROM table LIMIT 1", [], function(tx, result) {
      row = result.rows.item(0);
    }, function(tx, error) {
    });
  });

  return row;
}

Is this even possible? Can the Webkit storage API be set to synchronous instead of asynchronous execution?

+2  A: 

I think you want to create a closure here as values are being garbage collected/moved away from the scope chain before you can access them. Pass row to a closure for access later or to some other function that can handle the value while it's still in scope.

More info: Working With Closures

apphacker
A: 

Can the Webkit storage API be set to synchronous instead of asynchronous execution?

as far as I know, Webkit implements only asynchronous API of Web storage database API. There is no way to make it synchronous. Google Gears database API is synchronous.

Rafael
A: 

I wrote an example of this and other SQL transactions at: http://wecreategames.com/blog/?p=219

You have to do the WebKit executeSql calls in an asynchronous style. To get around this, you should have your:

function(tx, error) {
}

execute something to update your data. Something like:

function(tx, results) {
   console.log("Results returned: "+results.rows.length);
   for (var i=0; i<results.rows.length; i++) {
      var row = results.rows.item(i);
      document.getElementById('latestUpdated').innerHTML = row;
   } 
}

Notice that the second variable into the function isn't an error, it's the results.

I put in a for loop to show that there could be multiple results returned (probably not with that SQL statement, though) -- so hopefully you see the utility of it.

JayCrossler