Notebook
note 02: python vs javascript async/await
I've historically found async in Python a bit confusing. Partly because I haven't taken the time to fully understand it, partly because it actually is confusing. The async story in Python has gone through significant changes to reach where it is now.
The Event Loop
Javascript has an implicit event loop that's always running. This is not the case in Python.
When you do a setTimeout or setInterval, you're interacting directly with this global event loop.
In Python, you need to create this loop yourself.
async def main():
print('hello there')
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.close()
# or: send this to the event loop
asyncio.run(main())
Futures, Generators, Promises
In Python, async functions return coroutine objects when called. This is different from JS.
async function foo() {
console.log('hello there')
}
foo() // this logs 'hello there'
async def py_foo():
print('hello here')
coro = py_foo() # this just creates the coroutine object
# let's run the func
asyncio.create_task(coro)
asyncio.create_task runs the task without blocking
asyncio.run() or loop.run_until_complete blocks until finished