Wrapping webSql executeSql calls in a jQuery Deferred / Promise
Asked Answered
C

4

6

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?

Cilium answered 8/11, 2011 at 23:52 Comment(0)
Q
7

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

})()
Quan answered 4/5, 2012 at 18:43 Comment(2)
Hmmm. I would think you would call successWrapper(tx,data) instead of successWrapper(d). JavaScript is hard.Cilium
The challenge that I had faced was keeping the deferred object in scope, after calling executeSql. By creating a function that returns a function, I accomplished that goal.Quan
M
3

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: ;-[ ");

                    });

    }
};
Mayo answered 16/3, 2012 at 18:23 Comment(1)
Thanks Jacob! tutsplus.com/lesson/deferreds/?WT.mc_id=learnjquery talks about deferreds as well. I'm looking at your code and it falls in line with what Jeffrey Way says to do.Cilium
S
2

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); } );
Stulin answered 9/11, 2011 at 23:13 Comment(0)
V
2

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);
    });
Venetis answered 3/1, 2014 at 14:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.