我怎么能把它写成一个jQuery延迟函数

时间:2012-05-16 09:05:59

标签: jquery asynchronous jquery-deferred web-sql

我需要获取数据库中的所有表,然后逐个删除它们。但是每个DROP TABLE都是asnyc。 最重要的是只有在删除了所有表后才能解析返回的promise。

clear: function() {
    var dfd = $.Deferred();
    var sql = "SELECT name FROM sqlite_master WHERE type='table' AND name != ?",
    args = ["__WebKitDatabaseInfoTable__"];

    var dbTableNamesResult = function(tx, result) {
        var dropSql = "";
        for (var i = 0; i < result.rows.length; i++) {
            dropSql = "DROP TABLE IF EXISTS " + result.rows.item(i).name + "; ";
            execute(dropSql, null, errorCallback);
        }
    };

    execute(sql, args, dbTableNamesResult, dfd.reject);
    return dfd;
},

Execute有四个参数,sqlargumentssuccessCallbackerrorCallback

1 个答案:

答案 0 :(得分:1)

这个怎么样:

clear: function() {
    var dfd = $.Deferred();
    var sql = "SELECT name FROM sqlite_master WHERE type='table' AND name != ?",
    args = ["__WebKitDatabaseInfoTable__"];

    dfd.pipe(function(tx, result) {
        var deferreds = [];

        for (var i = 0; i < result.rows.length; i++) {
            var dfd = $.Deferred();
            dropSql = "DROP TABLE IF EXISTS " + result.rows.item(i).name + "; ";
            execute(dropSql, dfd.resolve, errorCallback);
            deferreds.push(dfd);
        }

        return $.when.apply(null, deferreds);
    });

    execute(sql, args, dfd.resolve, dfd.reject);
    return dfd;
},

以下是类似的示例http://jsfiddle.net/zerkms/XQwPq/

function getTables()
{
    var dfd = $.Deferred();

    $.ajax({
        url: '/echo/json/',
        data: {
            json: '{"tables":["a","b","c"]}',
            delay: 1
        },
        type: 'post',
        dataType: 'json',
        success: function(response) {
            dfd.resolve(response.tables);             
        }
    });

    return dfd;
}

function dropTables(tables)
{
    console.log('tables to delete: ' + tables.join(', '));

    var deferreds = [];

    for (var i = 0, len = tables.length; i < len; i++) {
        var dfd = $.Deferred();
        (function(dfd) {
            $.ajax({
                url: '/echo/json/',
                data: {
                    json: '{"table":"' + tables[i] + '"}',
                    delay: Math.random() * 3
                },
                type: 'post',
                dataType: 'json',
                success: function(response) {
                    console.log('table ' + response.table + ' deleted');
                    dfd.resolve();             
                }
            });
        })(dfd);

        deferreds.push(dfd);
    }

    return $.when.apply(null, deferreds);
}

getTables().pipe(dropTables).done(function() {
    console.log('process finished');
});
​

描述:第一个函数getTables返回带有ajax请求结果的延迟对象。我们使用它管道另一个函数dropTables,并在其中创建另一个延迟对象,它将接受N个延迟到其when。只要他们得到解决 - 显示最终匿名process finished