为什么这个异步代码在循环中不会中断?

时间:2017-08-31 07:55:15

标签: asynchronous tornado

我使用龙卷风异步http客户端,但它不起作用。

from tornado.concurrent import Future
import time
def async_fetch_future(url):
    http_client = AsyncHTTPClient()
    my_future = Future()
    fetch_future = http_client.fetch(url)
    fetch_future.add_done_callback(
        lambda f: my_future.set_result(f.result()))
    return my_future

future = async_fetch_future(url)
while not future.done():
    print '.....'
print future.result()

1 个答案:

答案 0 :(得分:1)

您必须运行事件循环以允许异步事件发生。您可以使用print IOLoop.current.run_sync(async_fetch_future(url)替换此while循环(但请注意,通常不需要手动处理此类Future个对象; async_fetch_future可以从Future返回AsyncHTTPClient.fetch直接,如果它需要做其他事情,用async_fetch_future装饰@tornado.gen.coroutine并使用yield会更加惯用。

如果你想做的事情不仅仅是在while循环中打印点,你应该使用定期执行yield tornado.gen.moment的协程:

@gen.coroutine
def main():
    future = async_fetch_future(url)
    while not future.done():
        print('...')
        yield gen.moment
    print(yield future)
IOLoop.current.run_sync(main)
相关问题