Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 318
user2058890 Avatar asked Feb 10 '13 14:02

user2058890


1 Answers

Nowadays, you can take advantage of async / await and promises like this:

async function alertResult() {
  const rows = await viewyearmain();
  if (rows.length) {
    alert("ROWS FOUND");
  } else {
    alert("ROWS NOT FOUND");
  }
}

function viewyearmain() {
  return new Promise(resolve => {
    db.transaction(function(tx) {
      tx.executeSql(
        "SELECT * FROM BUDGET WHERE holdingtype = ?;", ["month"],
        function(tx, result) { resolve(result.rows); },
        null
      );
    });
  });
}
like image 195
cilf Avatar answered Oct 15 '22 22:10

cilf