尝试创建另一个
Future并使用
add_done_callback:
从龙卷风文档
from tornado.concurrent import Futuredef 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
但是您仍然需要 使用ioloop解决未来 ,例如:
# -*- coding: utf-8 -*-from tornado.concurrent import Futurefrom tornado.httpclient import AsyncHTTPClientfrom tornado.ioloop import IOLoopdef async_fetch_future(): http_client = AsyncHTTPClient() my_future = Future() fetch_future = http_client.fetch('http://www.google.com') fetch_future.add_done_callback( lambda f: my_future.set_result(f.result())) return my_futureresponse = IOLoop.current().run_sync(async_fetch_future)print(response.body)另一种方法是使用
tornado.gen.coroutine装饰器,如下所示:
# -*- coding: utf-8 -*-from tornado.gen import coroutinefrom tornado.httpclient import AsyncHTTPClientfrom tornado.ioloop import IOLoop@coroutinedef async_fetch_future(): http_client = AsyncHTTPClient() fetch_result = yield http_client.fetch('http://www.google.com') return fetch_resultresult = IOLoop.current().run_sync(async_fetch_future)print(result.body)coroutine装饰器使函数返回
Future。



