Python & FastAPI•Part 3: Asynchronous Programming & Concurrency (26 - 40)
`wait()` vs `as_completed()` vs `shield()`:
In Simple Words:
as_completed(): Yields results as each task finishes, processing fastest responses first.wait(): Waits for tasks with return conditions (FIRST_COMPLETED,ALL_COMPLETED).shield(): Protects a critical coroutine from being cancelled by its caller.
python
# Process results as soon as each finishes:
async def process_fastest():
tasks = [fetch_api_a(), fetch_api_b(), fetch_api_c()]
for coro in asyncio.as_completed(tasks):
result = await coro
print("Got result:", result)