pythonadvanced
Run Async Tasks Concurrently with gather
Execute multiple async operations concurrently using asyncio.gather.
pythonPress ⌘/Ctrl + Shift + C to copy
import asyncio
import aiohttp
async def fetch_url(session, url):
async with session.get(url) as response:
data = await response.json()
return {"url": url, "status": response.status, "data": data}
async def main():
urls = [
"https://api.example.com/users",
"https://api.example.com/posts",
"https://api.example.com/comments",
]
async with aiohttp.ClientSession() as session:
# Run all requests concurrently
results = await asyncio.gather(
*[fetch_url(session, url) for url in urls],
return_exceptions=True
)
for result in results:
if isinstance(result, Exception):
print(f"Error: {result}")
else:
print(f"{result['url']}: {result['status']}")
asyncio.run(main())Use Cases
- Parallel API calls
- Concurrent I/O
- Batch processing
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonadvanced
Asyncio Semaphore and Timeout Patterns
Control concurrency with asyncio semaphores, timeouts, and task groups for robust async code.
Best for: rate limiting API calls
#python#asyncio
pythonintermediate
asyncio.gather Concurrent Tasks
Run multiple async operations concurrently with asyncio.gather and proper error handling.
Best for: Parallel API calls
#asyncio#concurrency
pythonintermediate
Python Concurrent Futures for Parallel Work
Run tasks in parallel using ThreadPoolExecutor and ProcessPoolExecutor with error handling.
Best for: Parallel HTTP requests for web scraping
#python#concurrency
pythonintermediate
Asyncio Concurrent
Advanced Python pattern: asyncio-concurrent
Best for: advanced programming
#python#advanced