Search code examples
javascriptweb-sql

WebSQL and Javascript Order of Operation


My application is using the javascript webSQL and I am having some issue with the order of command execution. No matter what order my code is in the querys get executed last. For example in the following code 2 will be alerted before 1:

db.transaction(
        function (transaction) {
        transaction.executeSql(
        'SELECT * FROM contacts WHERE id = ?;',
        [id],
        function (transaction, result) {
           alert("1");
           if (result.rows.length != 0) {
            user = result.rows.item(0).name;
           } else {}
        },
        errorHandler);
    });

alert("2");
message = id + '%1E' + name;

Any ideas why this is happen?


Solution

  • When do you alert("2"), you haven't finished the transaction, so the 2nd function you pass to it has not been called. Since it's the success handler I assume, it will be called after the transaction has completed successfully. The third argument would be the code snippet to execute when the query failed, only if it failed.

    Anything outside of the event handler code is executed when the page has loaded enough content to execute the javascript. Note that the entire page need not load to execute alert("2"), just enough of the JS. Since these statements are soooo close together, there is bascially 0 chance that the transaction will ever complete before the alert("2") statement is reached and executed.

    However, if you had enough code between alert("2") and db.transaction(...), it's possible (in what is called a race condition) that the callback could be executed before the alert(2) code.

    You want to be careful with event handlers in this case, although it depends on what your success handler does. If it modifies the page DOM, then I would highly recommend wrapping the db.transaction() and surrounding code) in an event handler that is bound to the page loading.