在Python Tornado中相当于jquery$
The equivalent of jquery $.when in Python Tornado
在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)
相关文章:
- 相当于 Jquery/Backbone.js 中的 Dgrid/Store (Dojo 工具包)
- Sidr.js相当于没有jQuery的AngularJS
- 纯Javascript:相当于jQuery$.data('key',value)
- 什么's相当于AngularJS中的jQuery.one()
- jQuery相当于Ajax调用中的onclick
- JavaScript 相当于 jQuery 的扩展方法
- jQuery相当于PHP的strtr
- Jquery相当于这个
- 相当于 jQuery 在 D3 中的 $(“.cell:first”)
- jQuery UI - 这相当于什么
- 有没有办法查看相当于jQuery方法的vanilla JavaScript
- Dojo相当于jQuery.text函数
- 相当于jquery赋值的纯javascript
- 在Python Tornado中相当于jquery$
- jQuery:相当于CSS的.live()
- 相当于Javascript中的jQuery代码
- 相当于c#在JavaScript (jQuery)中使用WCF方法
- SuperAgent相当于jquery的ajaxStart和ajaxStop
- jQuery相当于Ajax.Request,以及onSuccess和onComplete
- jQuery'相当于javascript'的传输是什么?Ajax请求中的responseText