Last active
August 29, 2015 14:08
-
-
Save alejandrobernardis/0300f54a9ead8a4e6415 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Testing with coroutines and yielding futures | |
This programs final ouptput is 3 | |
get_x, and get_y simulate an async task that returns later. | |
""" | |
import tornado.ioloop | |
from tornado.concurrent import Future | |
from tornado import gen | |
def get_x(): | |
print 'Get x' | |
f = Future() | |
ioloop = tornado.ioloop.IOLoop.instance() | |
ioloop.add_callback(_get_x, f) | |
return f | |
def _get_x(future): | |
print '_get_x' | |
future.set_result(2) | |
def get_y(): | |
print 'Get y' | |
f = Future() | |
ioloop = tornado.ioloop.IOLoop.instance() | |
ioloop.add_callback(_get_y, f) | |
return f | |
def _get_y(future): | |
print '_get_y' | |
future.set_result(1) | |
@gen.coroutine | |
def gen_futures(): | |
print 'gen_futures' | |
x = yield get_x() | |
print 'x: ', x | |
y = yield get_y() | |
print 'y: ', y | |
print x + y | |
def main(): | |
ioloop = tornado.ioloop.IOLoop.instance() | |
ioloop.run_sync(gen_futures) | |
ioloop.start() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment