3 ms·
Try to grasp coroutines outside the async/await framework. Alternatively, try to understand corutines within the framework as state machines, like so: asy
by formerly_proven 6y ago
Try to grasp coroutines outside the async/await framework. Alternatively, try to understand corutines within the framework as state machines, like so:
async def foo():
conn = await DB.connect()
results = await conn.query("SELECT bar, baz;")
restresult = await REST.get("somewhere.else.prod.example.net/v1/BAR", id=results.id)
return restresult.xyz
->
class foo():
future = None
conn = None
results = None
restresult = None
def call(self):
self.future = Future()
future = DB.connect()
future.add_done_callback(self._db_conn)
return self.future
def _db_conn(self, fut):
try:
self.conn = fut.get_result()
except:
self.future.set_exception()
return
future = self.conn.query("SELECT bar, baz;")
future.add_done_callback(self._results)
def _results(self, fut):
try:
self.results = fut.get_result()
except:
self.future.set_exception()
return
future = REST.get("somewhere.else.prod.example.net/v1/BAR", id=self.results.id)
future.add_done_callback(self._restresult)
def _restresult(self, fut):
try:
self.restresult = fut.get_result()
except:
self.future.set_exception()
return
self.future.set_result(self.restresult.xyz)
- jnwatson 6y agoI think this bottom-up approach is the best way to understand. Using libevent or libev for a while is a great way to understand the power of async. Async re-merges functions that have been shattered due to having to block.
- formerly_proven 6y agoThere are some projects which highlight what the language is doing versus what a library is implementing on top of that (e.g. asynker). I found that a great help in figuring out "what" async "is".
- croh 6y agoTwisted supports both styles, if I am not wrong. Top looks like inline callbacks api while bottom looks like normal defer api.