【问题标题】:jQuery .when not working as expected with rest operatorjQuery .when 无法使用 rest 运算符按预期工作
【发布时间】:2020-01-13 15:00:18
【问题描述】:

因此,在我们的代码库中,我们仅将 jquery 用于代码库的 ajax 部分,但我们希望包装所有调用,因此如果我们最终想摆脱 jquery,那么我们只需要更改实现即可。这是包装器的定义。

export const getAll = (...ajaxCalls) => {
    // return $.when($.ajax(ajaxCalls));
    return $.when(ajaxCalls.map(call => $.ajax(call)));
}

这就是我们所说的。

getAll(`/response/${customerId}`, `/response/${methods}`).done((response1, response2) => {
  console.log("getAll1",response1);
  console.log("getAll2",response2);
})

但是响应看起来像这样:

我对什么时候的理解是 response1 应该包含 response1 的 responseBody 和 response2 应该包含 response2 的 responseBody 但似乎并非如此。我错过了什么?

【问题讨论】:

    标签: javascript jquery ajax promise .when


    【解决方案1】:

    您似乎正在记录 jqHXR 对象,这可能是 jQuery.ajax()jQuery.when() 交互以提供结果 see last but one example here 的奇怪方式的结果。

    由于预期在稍后阶段清除 jQuery,我冒昧地建议您在此阶段需要标准化所有调用。这相当简单,只需使用.then() 而不是.done() 并期望结果以数组形式传递:

    getAll(`/response/${customerId}`, `/response/${methods}`)
    .then(results => {
        console.log("getAll0", results[0]);
        console.log("getAll1", results[1]);
    });
    

    然后,您需要在 getAll() 中跳几圈,以便标准化 jQuery.ajax()jQuery.when() 行为的各个方面:

    • 将 jQuery.when() 的传递结果标准化为单个参数而不是数组。
    • 将 jQuery.ajax() 的(data、statusText、jqXHR)交付标准化到其成功路径。
    • 标准化 jQuery.ajax() 将 (jqXHR, statusText, errorThrown) 传递到其错误路径。
    • 标准化jQuery.ajax() 的错误处理程序在不同版本的jQuery 中的行为。
    export const getAll = (...ajaxCalls) => {
        function makeAjaxCallAndStandardizeResponse(call) {
            return $.ajax(call)
            .then(
                // success handler: standardize success params
                (data, statusText, jqXHR) => data, // discard statusText and jqXHR
                // error handler: standardize error params and ensure the error does not remain "caught".
                (jqXHR, textStatus, errorThrown) => $.Deferred().reject(new Error(textStatus || errorThrown)).promise(); // discard jqXHR, and deliver Error object on the error path.
            );
        }
        // Aggregate with Promise.all() instead of jQuery.when() to cause a javascript Promise to be returned and results to be delivered as Array.
        return Promise.all(ajaxCalls.map(makeAjaxCallAndStandardizeResponse));
    }
    

    成功处理程序可能是不必要的,因为 Promise.all() 聚合会自动导致 statusTextjqXHR 被丢弃,但明确这些丢弃并没有真正的危害,除非您需要关注毫秒。

    从错误处理程序返回$.Deferred().reject(new Error(textStatus || errorThrown)).promise() 应该在所有版本的jQuery 中给出相同的行为,从而导致错误路径上传递一个错误对象。 (但记录的错误消息会有所不同)请务必对此进行测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 2019-09-23
      • 2021-08-07
      • 2013-06-23
      • 2018-11-14
      相关资源
      最近更新 更多