i currently use the client side database on an html5 iphone webapp. In my code i need to check if a row is present in the local DB :
function isStarted(oDB) {
var ret = null;
oDB.query(sql,params,function(transaction,result) {
if(result.rows.length > 0 ) {
ret = true;
} else {
ret = false;
}
});
return ret;
}
Unfortunately the return of isStarted() occurs before the callback function and i always get a "null" value. In the W3c spec we can see an "synchronous-database-api" but how can i use it ? Is there a trick to get the good "ret" value with asynchronus requets ?
Thanks for your help
XMLHttpRequest supports both synchronous and asynchronous communications. In general, however, asynchronous requests should be preferred to synchronous requests for performance reasons. Synchronous requests block the execution of code which causes "freezing" on the screen and an unresponsive user experience.
Synchronous request — (Default) Where the client blocks and waits for the result of the remote request before continuing execution. Asynchronous request — Where the client continues execution after initiating the request and processes the result whenever the AppServer makes it available.
Synchronous and asynchronous Operations performed using IndexedDB are done asynchronously, so as not to block applications.
JavaScript is Synchronous Spoiler: at its base, JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time.
To get an object implementing DatabaseSync
you have to call openDatabaseSync(...)
instead of openDatabase(...)
. I don't know about the iPhone, or what the oDB
object you have is, but according to spec you only get the openDatabaseSync
method in a WebWorker and not in the normal web browser window
. Certainly XMLHttpRequest
has demonstrated that potentially-length synchronous operations in the UI thread are not a good idea.
It's not possible to run asynchronous code synchronously, or vice versa. To do so you'd need language-level features like threads or co-routines that JavaScript doesn't have. You have to exit your functions and return control to the browser to allow it to perform the HTTP request or database query, and call you back on the handler function you gave it.
So you will have to rewrite your code ‘inside-out’ to pass callback functions instead of expecting return values, every time you do something involving database IO.
function tellMeWhenIsStarted(oDB, callback) {
oDB.query(sql,params,function(transaction,result) {
callback(result.rows.length>0);
}
});
I am the only one to find this asynchronous request ridiculous ? More over, it seems that Safari implements only the asynchronous model right now... I wonder how we efficiently code like that...
I would enjoy any link to serious programing with the async db driver.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With