在Python Tornado中相当于jquery$

The equivalent of jquery $.when in Python Tornado

本文关键字:jquery 相当于 Python Tornado      更新时间:2023-09-26

在jQuery中,$.when(promise1, promise2...)被用作主承诺,以表示其子承诺的总体状态。然后,我们可以将.done(callback)附加到$.when承诺,以便当所有promise1, promise2...完成时,将执行callback

在Python(Tornado)中,Future的行为类似于javascript中的promise,AsyncHTTPClient中的fetch()返回Future。

在下面的代码中,我有一个期货列表

from tornado.httpclient import AsyncHTTPClient
httpclient = AsyncHTTPClient()
futures = [
    httpclient.fetch("http://google.com")
    httpclient.fetch("http://example.com")
    httpclient.fetch("http://example.org")
]
def all_futures_done_callback():
    ...

当所有期货结束时,我如何执行all_futures_done_callback

在协同程序中,等待多个未来很容易;只需将它们全部作为列表:

@gen.coroutine
def f():
    futures = [
        httpclient.fetch("http://google.com")
        httpclient.fetch("http://example.com")
        httpclient.fetch("http://example.org")
    ]
    responses = yield futures

要用回调而不是协程来实现这一点,您需要类似于mgilson的答案。

在我看来,您需要自己构建此功能。这是未经测试的,但像这样的东西似乎应该起作用:

class FutureCollection(Future):
    def __init__(self, *args, **kwargs):
        super(FutureCollection, self).__init__(*args, **kwargs)
        self._waiting_for = []
    def _check_all_done_and_resolve(self, future):
        if all(f.done() for f in self._waiting_for):
            # Maybe check for exceptions a. la.
            # http://tornado.readthedocs.org/en/latest/_modules/tornado/concurrent.html#chain_future
            self.set_result(None)  # Not sure what the result should be.
    def add_future(self, future):
        self._waiting_for.append(future)
        future.add_done_callback(self._check_all_done_and_resolve)
    @property
    def futures(self):
        # Read-only access to the futures that have been added.
        return iter(self._waiting_for)