Asyncio Wait First Complete
Wait for the first of multiple tasks to complete with asyncio.wait for competitive fetching.
Code
import asyncio
async def fetch_from(source, delay):
await asyncio.sleep(delay)
return f'data from {source}'
async def fetch_first(sources):
tasks = [asyncio.create_task(fetch_from(s, d)) for s, d in sources]
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for t in pending:
t.cancel()
return next(iter(done)).result()
async def main():
result = await fetch_first([('cache', 0.1), ('db', 0.5), ('api', 1.0)])
print(result)What the code does
The working surface is the functions fetch_from, fetch_first and main — everything else is wiring.
Iteration happens inside for t in pending — everything outside it runs once. The async parts await their coroutines, which keeps ordering predictable.
What to watch for
- Plan for an install step:
asynciois a real dependency, resolved by the package manager.
Using it
The primary signature is def fetch_from(source, delay)
Import fetch_from from the file and call it — the rest of the code is implementation detail.
Key statements
async def fetch_from(source, delay):
await asyncio.sleep(delay)
return f'data from {source}'
async def fetch_first(sources):
tasks = [asyncio.create_task(fetch_from(s, d)) for s, d in sources]
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for t in pending:
t.cancel()
return next(iter(done)).result()
async def main():
result = await fetch_first([('cache', 0.1), ('db', 0.5), ('api', 1.0)])
print(result)
FAQ
- Are there third-party dependencies?
- `asyncio` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.