简体   繁体   中英

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?

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.

This isn't an answer to your question, but I thought I should give you a warning about webSQL.

As of 18 November 2010, W3C had announced that they have deprecated the Web SQL Database recommendation draft and will no longer maintain it.

So while it may WORK in browsers at the moment, I wouldn't rely on it for the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM