在我的项目中,我没有使用回调,而是尝试使用$ .Deferred在所有应用程序中都有统一的逻辑,我在代码中有很多地方可以执行以下操作:
function someMagicHandler(request) {
var me = this;
var sandbox = me.getSandbox();
var options = request.options;
var deferred = request.deferred;
var result = [];
var databaseOperation = sandbox.database.all('records').done(function (records) {
result.concat(records);
deferred.notify(records);
});
var serverResponse;
var serverOperation = sandbox.server.requestRecords(options).then(function (response) {
// First we are trying to save received records to database
serverResponse = response;
result.concat(response.Records);
deferred.notify(response.Records);
return sandbox.database.put('records', response.Records);
}).done(function() {
sandbox.storage.setTimestamp('records', new Date(serverResponse.Timestamp));
});
$.when(databaseOperation, serverOperation).then(deferred.resolve, deferred.reject);
}
在这段代码中,我个人不喜欢最后一行:
$.when(databaseOperation, serverOperation).then(deferred.resolve, deferred.reject);
是否有标准的表达方式:
$.when(databaseOperation, serverOperation).then(deferred);
这基本上意味着:
$.when(databaseOperation, serverOperation).then(deferred.resolve, deferred.reject, deferred.notify);
我已经更深入地研究了这个问题,并且只有当你不依赖于没有内存的deferred.progress()时才会解决下面的解决方案,因此在后续异步操作完成时不会返回任何数据同步。
如果您使用$ .Deferred()作为回调(即,当您依赖notify
或progress
函数并且在这种情况下,您需要将其作为参数传递)而不是您将有义务使用丑陋的
blahblahblah.then(deferred.resolve, deferred.reject, deferred.notify)
答案 0 :(得分:2)
你可以直接替换
$.when(databaseOperation, serverOperation).then(deferred.resolve, deferred.reject);
用这个:
request.deferred = $.when(databaseOperation, serverOperation);
并删除对变量deferred
的所有引用,因为$.when
已经为您创建了一个承诺(据我阅读本手册)。