1# test uasyncio.gather() function 2 3try: 4 import uasyncio as asyncio 5except ImportError: 6 try: 7 import asyncio 8 except ImportError: 9 print("SKIP") 10 raise SystemExit 11 12 13async def factorial(name, number): 14 f = 1 15 for i in range(2, number + 1): 16 print("Task {}: Compute factorial({})...".format(name, i)) 17 await asyncio.sleep(0.01) 18 f *= i 19 print("Task {}: factorial({}) = {}".format(name, number, f)) 20 return f 21 22 23async def task(id): 24 print("start", id) 25 await asyncio.sleep(0.2) 26 print("end", id) 27 28 29async def gather_task(): 30 print("gather_task") 31 await asyncio.gather(task(1), task(2)) 32 print("gather_task2") 33 34 35async def main(): 36 # Simple gather with return values 37 print(await asyncio.gather(factorial("A", 2), factorial("B", 3), factorial("C", 4))) 38 39 # Cancel a multi gather 40 # TODO doesn't work, Task should not forward cancellation from gather to sub-task 41 # but rather CancelledError should cancel the gather directly, which will then cancel 42 # all sub-tasks explicitly 43 # t = asyncio.create_task(gather_task()) 44 # await asyncio.sleep(0.1) 45 # t.cancel() 46 # await asyncio.sleep(0.01) 47 48 49asyncio.run(main()) 50