【问题标题】:jQuery $.wait() for *all* deferred's to be rejected?jQuery $.wait() for *all* deferred's 被拒绝?
【发布时间】:2020-03-07 22:45:47
【问题描述】:

jQuery 的Deferred API 有一个很好的功能,$.wait() 可以处理多个Deferreds / Promises。它在以下时间返回:

  • 所有的Deferreds 都是resolve()d

或

  • 一个 Deferreds 是reject()ed

大多数时候这是您想要的,但有时您想知道所有他们什么时候是reject()ed。

有没有一种简单或优雅的方式来做类似$.wait() 但只有在所有Deferreds 都被拒绝的情况下?

(可能还有其他用例,但我的是将其与 waiting for the first of several Deferred's to resolve 结合使用。)

【问题讨论】:

标签: jquery jquery-deferred


【解决方案1】:

本着 Promise 规范未来可能会采用 PromiseInspection 对象的精神,这里有一个 jQuery 附加函数,它可以告诉您所有承诺何时完成,无论是履行还是拒绝:

// pass either multiple promises as separate arguments or an array of promises
$.settle = function(p1) {
    var args;
    if (Array.isArray(p1)) {
          args = p1;
    } else {
        args = Array.prototype.slice.call(arguments);
    }

    function PromiseInspection(fulfilled, val) {
        return {
            isFulfilled: function() {
                return fulfilled;
            }, value: function() {
                return fulfilled ? val: undefined;
            }, reason: function() {
                return !fulfilled ? val: undefined;
            }
        };
    }
    return $.when.apply($, args.map(function(p) {
        // if incoming value, not a promise, then wrap it in a promise
        if (!p || (!(typeof p === "object" || typeof p === "function")) || typeof p.then !== "function") {
            p = $.Deferred().resolve(p);
        }
        // Now we know for sure that p is a promise
        // Make sure that the returned promise here is always resolved with a PromiseInspection object, never rejected
        return p.then(function(val) {
            return new PromiseInspection(true, val);
        }, function(reason) {
            // convert rejected promise into resolved promise
            // this is required in jQuery 1.x and 2.x (works in jQuery 3.x, but the extra .resolve() is not required in 3.x)
            return $.Deferred().resolve(new PromiseInspection(false, reason));
        });
    })).then(function() {
          // return an array of results which is just more convenient to work with
          // than the separate arguments that $.when() would normally return
        return Array.prototype.slice.call(arguments);
    });
}

然后,你可以这样使用它:

$.settle(promiseArray).then(function(inspectionArray) {
    inspectionArray.forEach(function(pi) {
        if (pi.isFulfilled()) {
            // pi.value() is the value of the fulfilled promise
        } else {
            // pi.reason() is the reason for the rejection
        }
    });
});

请记住,$.settle() 将始终完成(从不拒绝),并且完成的值是 PromiseInspection 对象的数组,您可以询问每个对象以查看它是完成还是拒绝,然后获取相应的值或原因。使用示例见下面的演示:

工作演示:https://jsfiddle.net/jfriend00/y0gjs31r/

【讨论】:

  • 似乎可以通过在 promise 拒绝时返回 Error(reason) 来改进/简化这段代码,如果它解决了则返回值,而不是处理 PromiseInspection。然后,在消费者中,您只需测试 result instanceof Error 即可找到最初拒绝的 Promise 并获取其拒绝原因。
  • @cjbarth - 是的,这是另一种方法。有些人喜欢这种方式,有些人喜欢这种方式。两者都工作正常。有一次,有一些标准讨论围绕使用类似 PromiseInspection 对象的这些类型的用途,但我不知道这是否仍然是一个可能的方向 - 这就是它这样做的原因。我同意,按照您建议的方式进行操作似乎更简单。这确实需要使用 instanceof Error 拒绝您使用的所有承诺的所有可能拒绝,这是合理的,但并非总是如此。
【解决方案2】:

我最近遇到了同样的问题:我认为这是因为 $.when 更像是 Promise.all 实现。

我无法在 jQuery 文档和整个网络中找到 Promise.allSettled 替代品,所以这是我的尝试:

const deferredsAllSettled = deferreds => {
    const settlements = [];

    deferreds.forEach(deferred => {
        const settlement = jQuery.Deferred();

        deferred.always(settlement.resolve);

        settlements.push(settlement);
    });

    const returnedDeferred = $.Deferred();

    jQuery.when
        .apply(jQuery, settlements)
        .then(() =>
            returnedDeferred.resolve(
                deferreds.map(deferred => deferred.promise())
            )
        );

    return returnedDeferred.promise();
};

注意:我已经为 utils 文件编写了它,所以 Promise.allSettled 一个唯一的 iterable 参数签名对我来说是可以的,如果你想用 $.when 精神写它(传递和获取$.Deferreds 作为单独的参数)你必须多写一点......

【讨论】:

  • 请在您的答案中添加相关代码,因为提供的链接在不久的将来可能无法使用。谢谢
猜你喜欢
  • 2013-11-14
  • 1970-01-01
  • 2019-09-19
  • 2011-01-24
  • 2015-05-19
  • 2017-10-14
  • 2017-08-08
  • 2017-02-25
  • 1970-01-01
相关资源
最近更新 更多