I’ve started using HTML5 and WebSQL, and I quickly ran into a problem: all the DB calls are asynchronous.
I come from PHP programming, where all the calls are synchronous, and I’m at a loss with the asynch stuff.
Basically, I open the DB and run a query, which uses an id parameter I’m passing to the page via GET (i.e. http://myserver.com/mypage.html?id=123). I need the result in globalResult:
id=window.location.search.substring(1).split('=')[1];
db=openDatabase("testDB", "1.0", "Test Database", 10000000);
db.transaction(function(tx)
{
tx.executeSql("SELECT * FROM testTable WHERE id="+id,[],successCB,errorCB);
});
function errorCB(tx,err)
{
alert("Error processing SQL: "+err);
}
function successCB(tx,result)
{
globalResult=result.rows.item(0)['description'];
}
...Javascript code which needs globalResult to be set...
Now, as the query is asynchronous, the interpreter starts executing the rest of the code before having the results, and of course it doesn’t work.
Is there any trick to run queries synchronously, or some technique to play with the callback functions in order to solve this problem?
Thanks in advance, guys 🙂
In the end, the easiest solution I found was to change the flow of the Javascript.
Instead of waiting for the results to populate my page (PHP-like), I went for a blank structure which gets populated in the end by the “success” callback function.
Also, I recommend using jquery-sql, which greatly simplifies the code when it comes to WebSQL.