0

I'm attempting to write a function to determine if an html5 websql db table is empty. Code is below. I put alerts in there to see what is happening. When this function runs the alert at bottom pops up first. Although the table is empty the return value is false.

function tableisempty() {
tf = false;
query = "SELECT * FROM OLL;";

localDB.transaction(function(transaction){
         transaction.executeSql(query, [], function(tx, results){

             if (results.rows.length == 0) { 
                  tf = true;
                  alert ("table has "+results.rows.length+" rows. returning "+tf);
                 }   else    {
                  tf = false;    
                  alert ("table is not empty. returning "+tf); 
                 }                               
         }, errorHandler);              
});

alert ("return value is " + tf);

return tf;

}

septemberbrain
  • 998
  • 9
  • 25

1 Answers1

0

Based on your comment and the w3 page, the query is happening async. The solution to your problem really depends on your js code structure.

Option 1:

Move tf outside the function (and add a var in front) and completely remove the return and alert right before it. When your callback gets called it will change the value of tf and the rest of your code can reference it is normal.

Option 2:

according to this SO question, you may be able to just change your call (elsewhere in your code I presume) from openDatabase to openDatabaseSync to enable synchronous operations.

Community
  • 1
  • 1
µBio
  • 10,668
  • 6
  • 38
  • 56