這樣如何:
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');
});
描述:推遲對象使用Ajax請求的結果第一功能getTables
回報。我們使用它管道另一個函數dropTables
並在其中創建另一個延遲對象,該對象將接受N遞延到其when
。只要他們解決了 - 最終匿名process finished
顯示爲
http://api.jquery.com/deferred.pipe/ –