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)Report a problem with this exampleOpens a pre-filled issue on GitHub.