Phonegap等待数据库事务完成

我正在创build一个将在第一次运行时执行不同的Phonegap应用程序。 我正在检测第一次运行的方式是通过查看其中一个数据库表存在。 正如你可能从下面的代码中可以看出,我正在检查(可能)表示表已经存在的错误,从而certificate这不是应用程序的第一次运行。

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代码的asynchronous执行意味着函数在成功(或错误)函数设置它的值之前返回其值。

这个函数在应用程序的初始化阶段被调用:

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

因此必须返回值而不是执行交易成功callback中的函数。

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

在此先感谢乔恩

你需要以callback的forms写下来:

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

你需要callback,但是如果不需要检查你的表的存在,你可以使用localStorage轻松完成。

例如

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

你将避免处理数据库。

也许这会有所帮助“CREATE TABLE IF NOT EXISTS …”

我知道会有程序员不喜欢我的解决scheme,但我喜欢它!

 var myfEspereti=false; function Espereti(pStatus) { if (pStatus==="wait") { myfEspereti = true; while(myfEspereti) { } } else if (pStatus==="go") { myfEspereti=false; } } 

然后打电话给Espereti(“等待”),等待asynchronous呼叫。 在asynchronous调用中,当它完成时,调用Espereti(“go”)就是这样!