繁体   English   中英

jQuery .when 与 rest 运算符不按预期工作

[英]jQuery .when not working as expected with rest operator

因此,在我们的代码库中,我们仅将 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 但情况似乎并非如此。 我错过了什么?

似乎您正在记录 jqHXR 对象,这可能是jQuery.ajax()jQuery.when()交互以提供结果的奇怪方式的结果,请参见最后一个示例

预计在稍后阶段会清除 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 中给出相同的行为,导致在错误路径上传递一个 Error 对象。 (虽然记录的错误消息会有所不同)请务必对此进行测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM