jQuery $ .wait()for * all * deferred’s被拒绝?
jQuery有一个很好的Deferred
API特性, $.wait()
用于处理多个Deferred
s / Promise
。 它返回时间:
- 所有
Deferred
s都已resolve()
d
要么
- 其中一个
Deferred
s已被reject()
编辑
大部分时间这都是你想要的,但有时你想知道他们所有人都被reject()
。
是否有一种简单或优雅的方式来执行$.wait()
但仅限于所有Deferred
s都被拒绝的情况?
(可能还有其他用例,但我的目的是将其与等待几个Deferred中的第一个解决 。)
本着PromiseInspection
对象如何使用Promise规范的精神,这里有一个jQuery附加function,可以告诉您何时完成所有承诺,无论是履行还是拒绝:
// 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/