Last active
March 9, 2017 19:51
-
-
Save jomido/5904830e481959a7002e6504c2f404a0 to your computer and use it in GitHub Desktop.
Asynchronous Equivalencies
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
| # NOTE: won't run, just an example | |
| # in all cases, we're trying to get to "# hooray" | |
| # asynchronous via Twisted's callbacks | |
| from wherever import bar, baz | |
| def foo(): | |
| df = bar() | |
| bar.addCallback(success_bar) | |
| bar.addErrback(fail_bar) | |
| def success_bar(result): | |
| df = baz(result) | |
| baz.addCallback(success_baz) | |
| baz.addErrback(fail_baz) | |
| def fail_bar(failure): | |
| pass | |
| def success_baz(result): | |
| # hooray | |
| pass | |
| def fail_baz(failure): | |
| pass | |
| # asynchronous via Twisted's inlineCallbacks | |
| from twisted.internet.defer import inlineCallbacks as asynchronous | |
| @asynchronous | |
| def foo(): | |
| try: | |
| result = yield bar() | |
| result = yield baz(result) | |
| # hooray | |
| except Exception as ex: | |
| pass | |
| # asynchronous via asyncio (Python 3) | |
| async def foo(): | |
| try: | |
| result = await asyncio.ensure_future(bar()) | |
| result = await asyncio.ensure_future(baz(result)) | |
| # hooray | |
| except Exception as ex: | |
| pass | |
| # asynchronous via asyncio futures (aka deferreds) | |
| def foo(): | |
| future = asyncio.ensure_future(bar()) | |
| future.add_done_callback(done_bar) | |
| def done_bar(future): | |
| try: | |
| result = future.result() | |
| future = asyncio.ensure_future(baz(result)) | |
| future.add_done_callback(done_baz) | |
| except Exception as ex: | |
| pass | |
| def done_baz(future): | |
| try: | |
| result = future.result() | |
| # hooray | |
| except Exception as ex: | |
| pass | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment