Async/Await with gather in Python
Level 5321 keystrokes
This uses async/await with asyncio.gather to run multiple coroutines concurrently and collect their results.
Python code
# Import asyncio for async operations1import asyncio2 # Define async function that simulates data fetching3async def fetch_data(name, delay): # Print start message4 print(f"Fetching {name}...") # Simulate network delay without blocking5 await asyncio.sleep(delay) # Return fetched data6 return f"{name} data"7 # Main async function to coordinate tasks8async def main(): # Create list of coroutines to run9 tasks = [ # First task with 1 second delay10 fetch_data("user", 1), # Second task with 2 second delay11 fetch_data("posts", 2), # Third task with 1 second delay12 fetch_data("comments", 1)13 ] # Run all concurrently (about 2 s total); results keep argument order14 results = await asyncio.gather(*tasks) # Print collected results15 print(f"Results: {results}")16 # Run the async main function17asyncio.run(main())Output
Fetching user... Fetching posts... Fetching comments... Results: ['user data', 'posts data', 'comments data']
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
"× 12(× 11)× 11,× 6.× 6_× 4:× 3{× 3}× 3=× 2