Question

I'm trying to write a way to synchronously execute a set of sqlite queries within a WebDB environment. I've come up with what I think amounts to a synchronous routine, but I'm not sure how to test it. Here's what I have:

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

On paper (I think) it should work. Looking at it, I think my alert message will pop up when the final statement is executed, not necessarily when it returns, but I'm not sure how to fix that. I tried specifying a callback in my arguments for the synchronousSql function but that meant I had to call it recursively with a callback, and if I used an empty anonymous function it seemed to overwrite the desired callback.

So I guess two questions: first, is this really synchronous; and second, how can I implement a final callback to run on the last callback of the stack?

edit: updated the code to a more recent version. First question still stands, though: is this truly synchronous?

Was it helpful?

Solution

Put an alert() and a setTimeout() in your code to test whether they all execute at the same time or get separated. That's usually a pretty good way to test it. If all code gets executed at the same time (async) then you'll instantly have 10 alerts to hide - else you get one per x ms.

On your second question: just check whether the stack is empty. You'll probably have to pass a third variable through your function though. Unless you define the variable on the global scope, it won't get overwritten.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top