我正在尝试编写一种在 WebDB 环境中同步执行一组 sqlite 查询的方法。我想出了我认为相当于一个同步例程的方法,但我不确定如何测试它。这是我所拥有的:
var db = openDatabase("test1", "1.0", "test", 5 * 1024 * 1024);
function synchronousSql(tx, sqlStack, callback) {
if (sqlStack.length !== 0) {
var q = sqlStack.shift();
console.log(+new Date() + ' ' + q);
tx.executeSql(q, [], synchronousSql(tx, sqlStack, callback), null);
} else {
callback();
}
}
var seq = [
'drop table if exists table1',
'drop table if exists table2',
'drop table if exists table3',
'drop table if exists table4',
'drop table if exists table5',
'create table table1(id integer, value text)',
'create table table2(id integer, value text)',
'create table table3(id integer, value text)',
'create table table4(id integer, value text)',
'create table table5(id integer, value text)',
'drop table if exists table1',
'drop table if exists table2',
'drop table if exists table3',
'drop table if exists table4',
'drop table if exists table5'
];
db.transaction(function(tx) {
synchronousSql(tx, seq, function() {
console.log(+new Date() + ' - from synchronousSql callback');
});
}, null, function() {
console.log(+new Date() + ' - from transaction callback');
});
在纸上(我认为)它应该有效。看着它,我认为我的警报消息会在执行最终语句时弹出,不一定在它返回时弹出,但我不知道如何解决这个问题。我尝试在synchronousSql
函数的参数中指定回调,但这意味着我必须使用回调递归地调用它,如果我使用一个空的匿名函数,它似乎会覆盖所需的回调。
所以我猜有两个问题:第一,这真的是同步的吗?其次,如何实现最终回调以在堆栈的最后一个回调上运行?
编辑:将代码更新为更新的版本。不过,第一个问题仍然存在:这真的是同步的吗?