Try creating another one Futureand use add_done_callback:
From the Tornado documentation
from tornado.concurrent import Future
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
But you still need to decide the future with ioloop , for example:
from tornado.concurrent import Future
from tornado.httpclient import AsyncHTTPClient
from tornado.ioloop import IOLoop
def 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_future
response = IOLoop.current().run_sync(async_fetch_future)
print(response.body)
Another way to do this is to use a decorator tornado.gen.coroutine, for example:
from tornado.gen import coroutine
from tornado.httpclient import AsyncHTTPClient
from tornado.ioloop import IOLoop
@coroutine
def async_fetch_future():
http_client = AsyncHTTPClient()
fetch_result = yield http_client.fetch('http://www.google.com')
return fetch_result
result = IOLoop.current().run_sync(async_fetch_future)
print(result.body)
coroutineThe decorator forces the function to return Future.
source
share