javascript - jquery $.when - 有什么方法可以阻止 .fail 提前触发吗?

标签 javascript jquery promise

根据 $.when 的 jQuery 文档,如果任何一个参数 promise 失败,那么 .when 不会等待,并且会立即失败。它也不会取消其他 promise 。

有没有办法强制 $.when 真正等待,直到所有 promise 都完成?或者,我可以/应该使用其他方法吗?

也许这是使用错误工具的情况,但我试图在同时获取两个部分的数据时阻止 UI(加载微调器)。我可以独立处理任一/两个部分的故障。当(且仅当)所有 promise 都完成(成功或失败)时,我想解锁该页面。

在下面的示例代码中,“callSvc”是一个测试方法,它采用字符串“service”标识符、以毫秒为单位的服务器 sleep 时间以及网络调用是否失败的指示符。

callSvc("sync", 0, false)
    .then(function (result) {
        return $.when(
            callSvc("ebill", 4000, false)
                .then(function (a, b, c, d) {
                    debugger;   
                }),
            callSvc("epol", 2000, true)
                .done(function () {
                    // set up epol section with data
                    debugger;
                })
                .fail(function () {
                    // set up epol section for failure
                    debugger;
                })
        ).done(function (ebill, epol) {
            // just here to test ways to stop early-fail
            debugger;
        }).fail(function () {
            // just here to test ways to stop early-fail
            debugger;
        })
    }).fail(function (err) {
        // show message
        debugger;   
    }).always(function () {
        // unblock the screen
        debugger;
    });

最佳答案

对于多参数 $.when()Promise.all,一旦任何调用失败,规范就会失败。然而,使用一个小的包装方法,您可以将失败变成(暂时的)成功。这相当于调用 catch,但使用两个参数 then 调用:

function wrapWithSuccessFlag(promise) {
  return promise.then(
      successfulValue => { return { success: true, value: successfulValue }; },
      failureReason => { return { success: false, reason: failureReason }; });
}

callSvc("sync", 0, false).then(result => {
    return $.when(
        wrapWithSuccessFlag(callSvc("ebill", 4000, false)
            .then(function (a, b, c, d) {
                debugger;   
            })),
        wrapWithSuccessFlag(callSvc("epol", 2000, true)
            .done(function () {
                // set up epol section with data
                debugger;
            })
            .fail(function () {
                // set up epol section for failure
                debugger;
            }))
    ).done(function (ebill, epol) {
        // Determine whether ebill and epol succeeded or failed.
        // You can also throw an error here using ebill or epol's reason,
        // which gets you the error handling you're used to.
    });

关于javascript - jquery $.when - 有什么方法可以阻止 .fail 提前触发吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51882205/

相关文章:

javascript - 在 React Native 应用程序中监听任意位置的点击

javascript - 嵌套循环 Angular.JS 使用复杂的嵌套循环

javascript - css 是背景色强制性的

带有函数原型(prototype)的 Javascript 命名空间声明

jquery - 当我点击一个div时如何禁用其他div

javascript - 当名称字段中包含 .(点)时,如何使用 angularjs 验证表单?

php - Jquery 无法将变量传递给 php

javascript - Express/React promise 陷入停滞

javascript - foreach 中的 promise

debugging - 如何使用 VS Code 调试器记录 Protractor 文本元素?