dal*_*ons 7 jquery promise jquery-deferred
所以在使用jQuery延迟并且$.when并行加载许多对象.
$.when(
a.ajax(), b.ajax(), c.ajax()
).then(
//do something when all are complete
complete();
);
Run Code Online (Sandbox Code Playgroud)
现在,b.ajax()有时会失败,但我真的不在乎.我只想等到所有调用完成后再调用complete().
不幸的是,一旦b失败,when()拒绝,并且永远不会触发then()回调.这是AFAIK的预期行为$.when(),但在这种情况下非常适合我.
我实际上想要一种说法:
$.when(
a.ajax(), b.ajax().fail(return success), c.ajax()
).then(...)
Run Code Online (Sandbox Code Playgroud)
或者可能有不同的使用方式when(),或更合适的构造?
如果要捕获promise的失败并将其转换为成功,则可以使用failFilter of then返回已解析的promise,如下所示:
deferredCall.then(function(answer) {
// this is success. you might transform the answer here.
return transformed;
}, function() {
// this is a fail. you might resolve the fail with an empty object.
return $.Deferred().resolve({}).promise();
});
Run Code Online (Sandbox Code Playgroud)
这样做可以确保链条可以不间断地继续经过故障.
因此,对于您的示例,您可能会这样做:
$.when([
a.ajax(),
b.ajax().then(function(answer) {
return answer;
}, function() {
return $.Deferred().resolve({}).promise();
}),
c.ajax()
]).then(function(results) {
// etc.
});
Run Code Online (Sandbox Code Playgroud)
实施例2:以我应用中,我有时用然后以获得关系数据为特定的实体并允许有404的可能性,以指示没有这种关系存在:
getEntity(id).then(function(entity) {
return getAssociation(id).then(function(association) {
entity.association = association;
return entity;
}, function() {
entity.association = null;
return $.Deferred().resolve(entity).promise();
});
}).done(function(entity) {
// etc.
});
Run Code Online (Sandbox Code Playgroud)
请注意,较旧的答案建议使用管道方法.从jQuery 1.8开始,不推荐使用此方法.