I’m using the HTML5 Web Database API and I have a function that checks to see if the app needs to go and perform it’s setup phase :
this.setupRequired = function() {
var status;
try {
this.db.transaction(function(tx) {
tx.executeSql("SELECT * FROM settings", [], function (tx,result) {
if (result.rows.length == 0) {
status = true;
} else {
status = false;
}
}, function(tx) {
status = true;
})
});
} catch (e) {
return true;
}
return status
}
I’d like to return true or false based on whether there is data in the settings table or not (or if the settings table doesn’t exist). The status var isn’t getting set, I’m guessing this is due to scope issues and the anonymous callback functions. I’m pretty sure I need to use a closure here to correct the issue but can’t quite get it right.
You can’t. It is not known whether there is data in the settings table at the time the
setupRequired()method has to return. This will only be known when the SQL database has performed the query and invoked the callback function. That happens only aftersetupRequired()and the functions that led to it being called have all exited, returning control to the browser.That’s the whole point of the callback function being passed to
executeSql(). The function is not executed right away, sostatuswill not have been touched by the timereturn statusis reached. What’s more, any exceptions that occur inside the callback functions will not cause thecatch(e)block to be executed, because thetry...catchblock will long have been exited by the time the function that was defined inside it is actually called. So thistry...catchis effectively useless.This is ‘asynchronous’ coding. Just because some code is below a function, doesn’t mean the function’s going to execute first.