简体   繁体   中英

Wrapping webSql executeSql calls in a jQuery Deferred / Promise

The html5 spec for executeSql includes a success callback and a fail callback:

db.transaction(function(tx) {    
    tx.executeSql('SELECT * FROM MyTable WHERE CategoryField = ?', 
    [ selectedCategory ], 
    function (tx, rs) { displayMyResult(rs); }, 
    function (tx, err) { displayMyError(err); } );
});

If I were using jQuery, is there a way to implement this using the new jQuery promise/deferred hotness?

I just wanted to add one more example.

(function () {
    // size the database to 3mb.
    var dbSize = 3 * 1024 * 1024,
        myDb = window.openDatabase('myDb', '1.0', 'My Database', dbSize);

    function runQuery() {
        return $.Deferred(function (d) {
            myDb.transaction(function (tx) {
                tx.executeSql("select ? as Name", ['Josh'], 
                successWrapper(d), failureWrapper(d));
            });
        });
    };

    function successWrapper(d) {
        return (function (tx, data) {
            d.resolve(data)
        })
    };

    function failureWrapper(d) {
        return (function (tx, error) {
            d.reject(error)
        })
    };

    $.when(runQuery()).done(function (dta) {
        alert('Hello ' + dta.rows.item(0).Name + '!');
    }).fail(function (err) {
        alert('An error has occured.');
        console.log(err);
    });

})()

Stumbled across this question while looking for something else, but I think I have some template code that will get you started wrapping webSql queries in jQuery Promises.

This is a sample sqlProviderBase to $.extend onto your own provider. I've got an example with a taskProvider and a page that would call to the taskProvider on the page show event. It's pretty sparse, but I hope it helps point others in the right direction for wrapping queries in a promise for better handling.

var sqlProviderBase = {

    _executeSql: function (sql, parms) {

        parms = parms || [];

        var def = new $.Deferred();

        // TODO: Write your own getDb(), see http://www.html5rocks.com/en/tutorials/webdatabase/todo/
        var db = getDb();

        db.transaction(function (tx) {
            tx.executeSql(sql, parms,
            // On Success
            function (itx, results) {
                // Resolve with the results and the transaction.
                def.resolve(results, itx);
            },
            // On Error
            function (etx, err) {
                // Reject with the error and the transaction.
                def.reject(err, etx);
            });
        });

        return def.promise();
    }
};

var taskProvider = $.extend({}, sqlProviderBase, {

    getAllTasks: function() {

        return this._executeQuery("select * from Tasks");

    }

});

var pageThatGetsTasks = {
    show: function() {

        taskProvider.getAllTasks()
                    .then(function(tasksResult) {

                        for(var i = 0; i < tasksResult.rows.length; i++) {
                            var task = tasksResult.rows.item(i);

                            // TODO: Do some crazy stuff with the task...
                            renderTask(task.Id, task.Description, task.IsComplete);

                        }

                    }, function(err, etx) {

                        alert("Show me your error'd face: ;-[ ");

                    });

    }
};

I find that wrapping the deferred transaction in a function and returning the promise creates a clean looking and reusable implementation of the deferred/promise pattern.

var selectCategory = function() {
    var $d = $.Deferred();

    db.transaction(
        function(tx) {
            tx.executeSql(
                "SELECT * FROM MyTable WHERE CategoryField = ?"
                , [selectedCategory]
                , success
                , error
            )
        }
    );

    function success(tx, rs) {
        $d.resolve(rs);
    }

    function error(tx, error) {
        $d.reject(error);
    }

    return $d.promise();
};

selectCategory()
    .done(function(rs){
        displayMyResult(rs);
    })
    .fail(function(err){
        displayMyError(err);
    });

I've been waiting for an answer, but nothing so far, so I'll take a shot. I can't run this so I apologize for any mistakes.

Are you looking for something like:

function deferredTransaction(db,transaction,transactionFunction(transaction)) {
    me=this;
    return $.Deferred(function(deferedObject){
        db.transaction(transactionFunction(transaction),
        function(tx,rs) { me.resolve(tx,rs); },
        function(tx,err) { me.reject(tx,err); } );
    }).promise();
}

dtx=deferredTransaction(db,tx,function(tx) {    
    tx.executeSql('SELECT * FROM MyTable WHERE CategoryField = ?', 
    [ selectedCategory ]);
dtx.then(function (tx, rs) { displayMyResult(rs); }, 
    function (tx, err) { displayMyError(err); } );

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