Jon Mulligan
Jon Mulligan

Reputation: 140

Phonegap wait for database transaction to complete

I'm creating a Phonegap application that will perform differently on first run. The way that I am detecting the first run is by seeing of one of the database tables exists. As you can probably tell from the code below, I am checking for the error that is (probably) indicating that the table already exists, thus proving that this is not the application's first run.

function databaseExists(){
var exists;
database.transaction(function(tx){
    tx.executeSql('CREATE TABLE GLOBAL (uid, property, value)');
}, function(err){
    exists = true;
}, function(){
    exists = false;
});
return exists;
}

My problem, however, is that the asynchronous execution of the Javascript code means that the function returns its value before the success (or error) function has set it's value.

This function is called in the initialising stage of the application:

if (databaseExists()){
    // Do Something
}

And therefore must return the value rather than execute the function in the success callback of the transaction.

Is there a way to force the execution to wait until the database transaction is complete or return the value through the database.transaction object?

Thanks in advance, Jon

Upvotes: 2

Views: 4783

Answers (3)

Ari Waisberg
Ari Waisberg

Reputation: 1303

I know there's gonna be programmers don't like my solution, but I love it!

var myfEspereti=false;

function Espereti(pStatus)
{
    if (pStatus==="wait")
    {
        myfEspereti = true;
        while(myfEspereti)
        {

        }
    }
    else if (pStatus==="go")
    {
        myfEspereti=false;
    }
}

and then call Espereti ("wait") when you want to wait for an async call. Inside the async call, when it's finish, call Espereti ("go") and that's it!

Upvotes: 0

Rymar
Rymar

Reputation: 11

You need callbacks, but if don't need checking existment of your tables, you can do that easily with localStorage.

e.g.

if(localStorage.getItem('init') === null){
   //init
   localStorage.setItem('init', true);
}

You will avoid dealing with database.

and maybe this gonna be helpful "CREATE TABLE IF NOT EXISTS..."

Upvotes: 0

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19049

You need to write it in callback form:

var dataBaseExists(yep, nope) {
  database.transaction(function(tx) {
    tx.executeSql('CREATE TABLE GLOBAL (uid, property, value)');
  }, function(){
    if (yep) {
      yep.apply(this, arguments);
    }
  }, function(){
    if (nope) {
      nope.apply(this, arguments);
    }
  });
};


var itDoes = function() {
  console.log("great");
};

var itDoesNot = function() {
  console.log("what a pity");
};


databaseExists(itDoes, itDoesNot);

Upvotes: 1

Related Questions