我需要获取数据库中的所有表,然后逐个删除它们。但是每个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
有四个参数,sql
,arguments
,successCallback
和errorCallback
。
答案 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