用 'null object' 替换 jQuery ajax 错误响应

Substitute jQuery ajax error response with a 'null object'

假设如下:

$.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!');
});

照原样,如果任一调用失败,.fail 处理程序将触发。我想要的是(以语法上优雅的方式)配置第二个 ajax 调用以用空对象替换错误响应(例如 {}[])。

我可以用 .always 替换 .done 处理程序,但这需要单独解析每个参数数组(getCriticalDatagetOptionalData)(n > 2).我正在寻找布尔状态 - 所有关键请求是否成功?

您需要 "catch" 第二个 ajax 的错误并确保错误处理程序将所需的恢复值传播到承诺链中。

与其他一些承诺库不同,jQuery 承诺没有 .catch() 方法,但您想要的在语法上仍然非常简单。 jQuery 的模式不是 $.ajax(...).catch(),而是 $.ajax(...).then(null, errorHandler),其中 errorHandler returns 承诺以所需的恢复值解决。

$.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!');
});