0

我需要一些类似于 JS 的Promise.all()的扭曲的东西。我找到了这个FireWhenAllFinish示例,但它有问题(抛出异常,可能已过时)。

这不是一个真正的问题,因为我找到了解决方案,见下文。仍然在此处发布,以便对其他人有所帮助。

4

2 回答 2

0

我最后想出了这个:

class DeferredAll(Deferred):
    def __init__(self, deferreds):
        super(DeferredAll, self).__init__()
        assert deferreds, 'Need at least one deferred for DeferredAll'
        self.deferreds = deferreds
        self._results = []
        self.finished_count = 0

        for d in self.deferreds:
            d.addCallbacks(self._success, self._fail)

    def _success(self, result):
        self.finished_count += 1
        # print('_success {}/{} {}'.format(self.finished_count, len(self.deferreds), result))
        self._results.append(result)
        if self.finished_count == len(self.deferreds):
            self.callback(self._results)

    def _fail(self, *args, **kwargs):
        # print('_fail {} {}'.format(str(args), str(kwargs)))
        if not self.called: # this property is True if callback()/errback() has already been called
            self.failed = True
            self.errback()
于 2018-01-12T00:05:44.220 回答
0

Twisted 中有几个解决方案:

from __future__ import print_function

from twisted.internet.defer import DeferredList, gatherResults, succeed

DeferredList([succeed(1), succeed(2)]).addCallback(print)
gatherResults([succeed(1), succeed(2)]).addCallback(print)
于 2018-01-12T12:26:24.437 回答