import asyncio
async def get_user_data():
# We must use await and asyncio.sleep.
# Standard time.sleep() would block the entire program here.
await asyncio.sleep(1)
return {"name": "Michael"}
async def get_posts():
await asyncio.sleep(1)
return ["Post 1", "Post 2"]
def render_page(user_data, posts):
return f"User: {user_data['name']}, Posts: {len(posts)}"
async def main():
# We have to explicitly tell asyncio to run these together.
# If we just awaited them one by one, they would run sequentially.
user_data, posts = await asyncio.gather(get_user_data(), get_posts())
# Then we manually pass the results to the next function
result = render_page(user_data, posts)
print(result)
if __name__ == "__main__":
# We have to manually start the event loop
asyncio.run(main())
Mainly the having to manage the async def function and those can not be used with normal def function (at least not easily) and how the main() loop works in that one, where you have to await asyncio.gather() and asyncio.run() it can start to get REALLY complicated REALLY fast.
Here is that exact example with standard asyncio
Mainly the having to manage the
async def functionand those can not be used with normaldef function(at least not easily) and how themain()loop works in that one, where you have toawait asyncio.gather()andasyncio.run()it can start to get REALLY complicated REALLY fast.wovemakes it clean and easy.