Phonegap等待数据库事务完成 [英] Phonegap wait for database transaction to complete

查看:180
本文介绍了Phonegap等待数据库事务完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个Phonegap应用程序,将在第一次运行时执行不同。我检测第一次运行的方式是通过查看其中一个数据库表存在。从下面的代码可以看出,我检查的错误是(可能),表明该表已经存在,因此证明这不是应用程序的第一次运行。

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

但我的问题是,Javascript代码的异步执行意味着该函数在成功(或错误)函数设置其值之前返回其值。



此函数在应用程序初始化阶段调用:

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



因此必须返回值,而不是在事务的成功回调中执行函数。



有没有办法强制执行等待数据库事务完成或通过database.transaction对象返回值?



感谢提前,
Jon

解决方案

您需要以回调形式写入:

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


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

解决方案

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

这篇关于Phonegap等待数据库事务完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆