Suppose the following:
假设如下:
$.when(
$.ajax({
url: '/this/one/is/critical'
}),
$.ajax({
url: '/can/live/without'
}) // recoverable failure
).done(function (getCriticalData, getOptionalData) {
console.log('we are done.');
}).fail(function () {
console.error('it cannot be done!');
});
As-is, if either call fails the .fail
handler will fire. What I want is to (in a syntactically elegant way) configure the second ajax call to substitute error responses with a null object (e.g. {}
or []
).
原样,如果任一调用失败,.fail处理程序将触发。我想要的是(以语法上优雅的方式)配置第二个ajax调用以用空对象替换错误响应(例如{}或[])。
I could replace .done
handler with .always
but that requires parsing each array of parameters (getCriticalData
and getOptionalData
) individually (which can get ugly with n > 2). I'm looking for a boolean state - did all critical requests succeed or not?
我可以用.always替换.done处理程序,但这需要单独解析每个参数数组(getCriticalData和getOptionalData)(这可能会因n> 2而变得难看)。我正在寻找一个布尔状态 - 所有关键请求都成功了吗?
1 个解决方案
#1
2
You need to "catch" the second ajax's error and ensure the error handler propagates the desired recovery value down the promise chain.
您需要“捕获”第二个ajax的错误,并确保错误处理程序在promise链中传播所需的恢复值。
Unlike in some other promise libs, jQuery promises don't have a .catch()
method, but what you want is still syntactically very simple. Instead of $.ajax(...).catch()
, jQuery's pattern is $.ajax(...).then(null, errorHandler)
, in which errorHandler
returns a promise resolved with the desired recovery value.
与其他一些承诺库不同,jQuery承诺没有.catch()方法,但你想要的仍然在语法上非常简单。而不是$ .ajax(...)。catch(),jQuery的模式是$ .ajax(...)。then(null,errorHandler),其中errorHandler返回一个用所需恢复值解析的promise。
$.when(
$.ajax({
url: '/this/one/is/critical'
}),
$.ajax({
url: '/can/live/without'
}).then(null, function() {
return $.when([]); // return a new promise resolved with a recovery value.
})
).done(function (getCriticalData, getOptionalData) {
console.log('we are done.');
}).fail(function () {
console.error('it cannot be done!');
});
#1
2
You need to "catch" the second ajax's error and ensure the error handler propagates the desired recovery value down the promise chain.
您需要“捕获”第二个ajax的错误,并确保错误处理程序在promise链中传播所需的恢复值。
Unlike in some other promise libs, jQuery promises don't have a .catch()
method, but what you want is still syntactically very simple. Instead of $.ajax(...).catch()
, jQuery's pattern is $.ajax(...).then(null, errorHandler)
, in which errorHandler
returns a promise resolved with the desired recovery value.
与其他一些承诺库不同,jQuery承诺没有.catch()方法,但你想要的仍然在语法上非常简单。而不是$ .ajax(...)。catch(),jQuery的模式是$ .ajax(...)。then(null,errorHandler),其中errorHandler返回一个用所需恢复值解析的promise。
$.when(
$.ajax({
url: '/this/one/is/critical'
}),
$.ajax({
url: '/can/live/without'
}).then(null, function() {
return $.when([]); // return a new promise resolved with a recovery value.
})
).done(function (getCriticalData, getOptionalData) {
console.log('we are done.');
}).fail(function () {
console.error('it cannot be done!');
});