簡體   English   中英

在Python Tornado中相當於jquery $ .when

[英]The equivalent of jquery $.when in Python Tornado

在jQuery中$.when(promise1, promise2...)作主承諾 ,代表其子承諾的整體狀態。 然后,我們可以在$.when promise1, promise2...承諾promise1, promise2... .done(callback)附加到$.when promise1, promise2...承諾上,以便當所有promise1, promise2...完成時,將執行callback

在Python(Tornado)中, Future行為類似於javascript中的promise,並且AsyncHTTPClientfetch()返回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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM