javascriptsqliteasynchronoussynchronousweb-sql

How to make a WebSQL query synchronous?


Consider:

var globalvar;

function viewyearmain() {
  db.transaction(function (tx) 
  {
    tx.executeSql('SELECT * FROM BUDGET WHERE holdingtype="month"', [], function (tx, results) 
    {
       var len = results.rows.length;
       msg = len;
       globalvar = msg;
    }, null);

  });

  if (globalvar>0)
  {
    alert("ROWS FOUND");
  }
  else
  {
    alert("ROWS NOT FOUND");
  }
}

The problem is that ROWS NOT FOUND appears because the transaction has not completed by the time the if statement is reached.


Solution

  • An asynchronous callback is not synchronous, regardless of how much you want it to be.

    Just move all the code the depends on the result into the callback:

    var globalvar;
    
    function viewyearmain() {
      db.transaction(function (tx) 
      {
        tx.executeSql('SELECT * FROM BUDGET WHERE holdingtype="month"', [], function (tx, results) 
        {
           var len = results.rows.length;
           msg = len;
           globalvar = msg;
           if (globalvar>0)
           {
             alert("ROWS FOUND");
           }
           else
           {
             alert("ROWS NOT FOUND");
           }
        }, null);
    
      });
    }
    

    Alternatively, move it into a second function, and call that from the callback.