这个怎么样:
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
显示最终的匿名与