Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import asyncio
- from random import randint
- apis = (
- 'api1',
- 'api2',
- 'api3',
- 'api4',
- )
- async def worker(fp, api):
- t = randint(1,5)
- await asyncio.sleep(t)
- return f'retrieved from {api} after {t} seconds'
- async def get_fastest_result(fp):
- done, pending = await asyncio.wait(tuple(worker(fp, api) for api in apis), return_when=asyncio.FIRST_COMPLETED)
- ret = done.pop()
- for i in pending:
- i.cancel()
- if ret:
- return ret.result()
- async def main():
- fp = 'this is a file path'
- ret = await get_fastest_result(fp)
- print(ret)
- if __name__ == '__main__':
- loop = asyncio.get_event_loop()
- loop.run_until_complete(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement