简体   繁体   English

通用方法推迟所有?

[英]Generic approach to deferred all?

I need something in twistd similar to JS' Promise.all() . 我需要类似JS'Promise.all()的东西 I found this FireWhenAllFinish example, but it is buggy (throws exceptions, maybe outdated). 我找到了这个FireWhenAllFinish示例,但是它有很多错误(抛出异常,也许已经过时)。

This is not really a question, cause I found a solution, see below. 这不是一个真正的问题,因为我找到了解决方法,请参阅下文。 Still posting it here so it might help others. 仍将其张贴在这里,这样可能会对其他人有所帮助。

I came up with this in the end: 我最终想到了这个:

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()

There are a couple solutions for this in Twisted: 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM