Pandaaaa906

get_fastest_result

Feb 2nd, 2021
866
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import asyncio
  2. from random import randint
  3.  
  4. apis = (
  5.     'api1',
  6.     'api2',
  7.     'api3',
  8.     'api4',
  9. )
  10.  
  11. async def worker(fp, api):
  12.     t = randint(1,5)
  13.     await asyncio.sleep(t)
  14.     return f'retrieved from {api} after {t} seconds'
  15.  
  16. async def get_fastest_result(fp):
  17.     done, pending = await asyncio.wait(tuple(worker(fp, api) for api in apis), return_when=asyncio.FIRST_COMPLETED)
  18.     ret = done.pop()
  19.     for i in pending:
  20.         i.cancel()
  21.     if ret:
  22.         return ret.result()
  23.  
  24. async def main():
  25.     fp = 'this is a file path'
  26.     ret = await get_fastest_result(fp)
  27.     print(ret)
  28.  
  29. if __name__ == '__main__':
  30.     loop = asyncio.get_event_loop()
  31.     loop.run_until_complete(main())
  32.  
RAW Paste Data