$ .Deferred:当每一个承诺一直执行如何检测 [英] $.Deferred: How to detect when every promise has been executed

查看:238
本文介绍了$ .Deferred:当每一个承诺一直执行如何检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些需要完成的任务异步,所以我使用的承诺。

I have a number of async tasks that need to be completed, so I'm using promises.

我需要的时候承诺的每一个已被执行(既解决,拒绝)来检测。我不能继续执行,直到这一点。

I need to detect when each one of the promises has been executed (both resolved and rejected). I must not continue execution until that point.

我用的是这样的:

$.when(promise1, promise2, ...).always();

但是,这code是错误的,因为方法有懒惰的评价,而且一旦承诺之一失败返回。因此,总是的回调也只要承诺之一故障运行。

But this code is wrong, because the when method has lazy evaluation, and it returns as soon as one of the promises fails. So the always callback also runs as soon as one of the promises fail.

我想在编写一个解决办法,但这种使用情况是如此普遍,也许有人已经做它已经,或者也许有这样做只使用jQuery的(如果不是,那将是很好的添加,甚至一种方式 Promise.whenNonLazy Promise.when(promise1,promise2,...,FALSE)的未来。

I was thinking in coding a workaround, but this use case is so common that maybe somebody has done it already, or maybe there's even a way of doing this using just jQuery (if not, it would be nice to add a Promise.whenNonLazy or a Promise.when(promise1, promise2, ..., false) in the future.

这可能吗?

推荐答案

更​​复杂的诺言库拥有的 allSettled()之类的函数问: 或的 Promise.settle 像蓝鸟

More sophisticated promise libraries have an allSettled() function like Q or Promise.settle like Bluebird.

在jQuery的,你可以实现这样的自己功能以及与它延长 $ 的命名空间,但如果你需要经常和性能 - 这只会是必要的优化。

In jQuery, you could implement such a function yourself as well and extend the $ namespace with it, but that will only be necessary if you need it often and performance-optimized.

有一个简单的解决方案是创建为每个正在等待的人的一个新的承诺,履行他们即使在底层的一个拒绝。然后你可以使用 $。当()对他们没有任何问题。简而言之:

A simpler solution would be to create a new promise for each of the ones you are waiting for, and fulfilling them even when the underlying one is rejected. Then you can use $.when() on them without problems. In short:

// using Underscore's .invoke() method:
$.when.apply(null, _.invoke(promises, "then", null, $.when)).done(…)

更稳定:

$.when.apply($, $.map(promises, function(p) {
    return p.then(null, function() {
        return $.Deferred().resolveWith(this, arguments);
    });
})).then(…);

您可能会更改然后回调位在履行并拒绝结果区别开来最终完成

You might change the then callbacks a bit to distinguish between fulfilled and rejected results in the final done.

这篇关于$ .Deferred:当每一个承诺一直执行如何检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆