Phonegap wait for database transaction to complete

牧云@^-^@ 提交于 2019-12-11 03:12:25

问题


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


回答1:


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);



回答2:


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..."




回答3:


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!



来源:https://stackoverflow.com/questions/12059916/phonegap-wait-for-database-transaction-to-complete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!