在我开始破解我的代码之前,只是想知道。例如:
if (blahblah) {
$.ajax("randomthingy1");
}
if (blahblahblah) {
$.ajax("randomthingy2");
}
// Use jQuery to test when they've both finished. Obviously they won't always both finish, as they might not both exist, and none of them might exist either.
$.when($.ajax("randomthingy1"), $.ajax("randomthingy2"), function (stuff) {
// foo
}
// Might produce an error, as one might not exist. But will it move on and not bother?
只是想知道。如果它确实需要创建错误并停止执行,是否有办法捕获错误并继续?
答案 0 :(得分:2)
.when()
将仅触发done() handler
。因此,在您的实例中,如果一个 Ajax请求因任何原因失败,那么混合的 Deferred 对象将解析为失败并且您的处理程序通过{绑定{1}}不会开火。但当然,在.when() -> done
或fail
绑定的所有处理程序都会触发。
always
答案 1 :(得分:1)
我不确定这会回答你的问题,但这就是我如何处理这些事情:
var requests = [];
if (blahblah) {
requests.push( $.ajax("randomthingy1") );
}
if (blahblahblah) {
requests.push( $.ajax("randomthingy2") );
}
$.when.apply( $, requests ).then( function( ) {
// handle success
}, function( ) {
// handle error
});
这确保代码将进入处理程序,即使这些条件都不满足,即请求不存在。
答案 2 :(得分:0)
您可以使用此布局确保始终响应延期完成,无论是否已解决或拒绝:
$.when(deferred1, deferred2, ...)
.done(function (data1, data2, ...) {
// success handlers - fires if all deferreds resolve
})
.fail(function (error1, error2, ...) {
// failure handlers - fires if one or more deferreds reject or throw exceptions
})
.always(function () {
// complete handlers - always fires after done or fail
});