将 webSqlexecuteSql 调用包装在 jQuery Deferred / Promise 中

发布于 2024-12-14 19:56:30 字数 370 浏览 0 评论 0原文

executeSql 的 html5 规范包括成功回调和失败回调:

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

如果我使用 jQuery,有没有办法使用新的 jQuery Promise/Deferred Hotness 来实现此功能?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

喜爱皱眉﹌ 2024-12-21 19:56:30

我只是想再添加一个例子。

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

})()

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

})()
紫竹語嫣☆ 2024-12-21 19:56:30

在寻找其他东西时偶然发现了这个问题,但我想我有一些模板代码可以让您开始在 jQuery Promises 中包装 webSql 查询。

这是将 $.extend 扩展到您自己的提供程序的示例 sqlProviderBase。我有一个带有 taskProvider 的示例和一个在页面显示事件上调用 taskProvider 的页面。它非常稀疏,但我希望它可以帮助其他人指明正确的方向,以包装查询以保证更好的处理。

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

                    });

    }
};

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

                    });

    }
};
离去的眼神 2024-12-21 19:56:30

我一直在等待答案,但到目前为止还没有任何消息,所以我会尝试一下。我无法运行此程序,因此对于任何错误我深表歉意。

您是否正在寻找类似的东西:

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

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); } );
孤独难免 2024-12-21 19:56:30

我发现将延迟事务包装在函数中并返回承诺会创建一个外观简洁且可重用的延迟/承诺模式实现。

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 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);
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文