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;

}

4
  • 1
    @GolezTrol yes. diveintohtml5.org/storage.html for example Commented Oct 4, 2011 at 20:32
  • I learned something today. :) Commented Oct 4, 2011 at 20:34
  • So when the first alert hits, it says "table has 0 rows. returning false"? Commented Oct 4, 2011 at 21:00
  • First alert is "return value is false", 2nd alert says "table has 0 rows. returning true". But returned value is false. Commented Oct 4, 2011 at 21:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.