我正在使用PhoneGap和SQLite数据库。
我尝试这样的事情:
我有一个函数useSavedThing():
function useSavedThing() {
alert("BEFORE getSavedThing()");
getSavedThing();
alert("AFTER getSavedThing()");
}
和函数getSavedThing():
function getSavedThing(){
alert("ONE");
var db = window.openDatabase("Database", "1.0", "Database", 200000);
db.transaction(populateDB, errorCB, successCB);
alert("TWO");
function populateDB(tx) {
alert("THREE");
}
function errorCB(tx, err) {
alert("Error processing SQL: " + err);
}
function successCB() {
alert("FOUR");
db.transaction(getData);
}
function getData(tx) {
alert("FIVE");
tx.executeSql('SELECT * FROM SETTINGS', [], getIt, errorCB);
}
function getIt(tx, results) {
alert("SIX");
var savedthing = results.rows.item(0).data;
}
}
问题是当调用函数getSavedThing()时,只发出前两个警报(alert(“ONE”),alert(“TWO)”),然后调用警报(“AFTERSaveThing()”)。
但我希望所有费用提醒(“ONE”),提醒(“TWO”),提醒(“TREE”)提醒(“FOUR”)提醒(“FIVE”),提醒(“SIX”),已发出在警报之前(“在getSavedThing()之后”); appers。
警报的顺序应为:
有人可以帮助我吗?
答案 0 :(得分:1)
数据库操作是异步执行的。如果您希望在最后一次数据库操作之后执行alert("AFTER getSavedThing()")
,则需要从回调函数getIt()
调用它;
function useSavedThing() {
alert("BEFORE getSavedThing()");
var afterGet = function(){
alert("AFTER getSavedThing()");
}
getSavedThing( afterGet ); /*pass the callback function to getSavedThing*/
}
function getSavedThing( callback ){
alert("ONE");
var db = window.openDatabase("Database", "1.0", "Database", 200000);
db.transaction(populateDB, errorCB, successCB);
alert("TWO");
function populateDB(tx) {
alert("THREE");
}
function errorCB(tx, err) {
alert("Error processing SQL: " + err);
}
function successCB() {
alert("FOUR");
db.transaction(getData);
}
function getData(tx) {
alert("FIVE");
tx.executeSql('SELECT * FROM SETTINGS', [], getIt, errorCB);
}
function getIt(tx, results) {
alert("SIX");
var savedthing = results.rows.item(0).data;
callback.call(); /*execute the callback function*/
}
}
答案 1 :(得分:0)
您可以在PhoneGap中使用this framework进行数据访问,您会发现它非常易于使用:
var db = new MyDB();
//query all users
var users = db.Users.toArrary(callback);