Using WebSQL with async.js, resulting in InvalidStateError

508 views Asked by At

I'm trying to use the WebSQL API with async.js to make it easier to use. I use the method async.waterfall() to pass the transaction object from one function to another. Here's a simple example:

async.waterfall([function(callback) {
    db.transaction(function(tx) {
        callback(null, tx);
    }, onError);

}, function(tx, callback) {
    tx.executeSql('SELECT * FROM sqlite_master', [], function(tx, rs) {
        callback(null, tx, rs);
    }, onError);

}], function(tx, rs) {
    // do something with rs.rows

});

When I call tx.executeSql() Chrome's console says: Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.
Very likely this refers to the tx object.

Using WebSQL the traditional way (creating a 'function waterfall') works fine. Is there something I have to pay attention to using WebSQL in a way like that? Or are there better alternatives?

1

There are 1 answers

1
Andreas Linnert On BEST ANSWER

Okay, I found out WebSQL doesn't work with async.waterfall() for some reason. The following code, using async.series(), works fine. Also when you wrap the function transaction() around a waterfall() it doesn't work.

Still, waterfall() would be nice in some cases...

Working example with series() inside transaction():

db.transaction(function(tx) {
    async.series([
        function(callback) {
            tx.executeSql('DROP TABLE IF EXISTS colors', [],
                function(tx, rs) { callback(null, rs); },
                function(err) { callback(err); });
        },
        function(callback) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS colors (name, red, green, blue)', [],
                function(tx, rs) { callback(null, rs); },
                function(err) { callback(err); });
        },
        function(callback) {
            tx.executeSql('INSERT INTO colors VALUES ("red", 255, 0, 0)', [],
                function(tx, rs) { callback(null, rs); },
                function(err) { callback(err); });
        },
        function(callback) {
            tx.executeSql('SELECT * FROM colors', [],
                function(tx, rs) { callback(null, rs); },
                function(err) { callback(err); });
        }
    ],
    function(err, results) {
        if (!!err) { onError(err); }

        console.debug(results[3].rows.item(0));
    });
});