1

我需要获取数据库中的所有表,然后将它们一一删除。但是每个DROP TABLE都是异步的。最重要的是,只有在删除所有表时才应解决返回的承诺。

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

4

1 回答 1

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显示最终的匿名与

于 2012-05-16T09:36:07.013 回答