Aller au contenu

Await in loop (ARCH2030)

Ce contenu n’est pas encore disponible dans votre langue.

Key python.async.await-in-loop · Severity info · Category async

Awaiting each element inside a loop body serializes independent async operations. With asyncio.gather they can run concurrently, cutting total latency.

async def load_all(ids):
results = []
for i in ids:
results.append(await fetch(i)) # serial
return results
import asyncio
async def load_all(ids):
return await asyncio.gather(*(fetch(i) for i in ids)) # concurrent

Collect independent calls with asyncio.gather and await them concurrently in one pass.