1. from usr import uasyncio as asyncio
    2. async def barking(n):
    3. print('Start barking')
    4. for _ in range(6):
    5. await asyncio.sleep(1)
    6. print('Done barking.')
    7. return 2 * n
    8. async def foo(n):
    9. print('Start timeout coro foo()')
    10. while True:
    11. await asyncio.sleep(1)
    12. n += 1
    13. return n
    14. async def bar(n):
    15. print('Start cancellable bar()')
    16. while True:
    17. await asyncio.sleep(1)
    18. n += 1
    19. return n
    20. async def do_cancel(task):
    21. await asyncio.sleep(5)
    22. print('About to cancel bar')
    23. task.cancel()
    24. async def main():
    25. tasks = [asyncio.create_task(bar(70))]
    26. tasks.append(barking(21))
    27. tasks.append(asyncio.wait_for(foo(10), 7))
    28. asyncio.create_task(do_cancel(tasks[0]))
    29. res = None
    30. try:
    31. # return_exceptions=True, 默认为False,即在任何协程引发异常时立即中止并引发异常。 如果设置为True,则将异常包装在结果中返回。
    32. res = await asyncio.gather(*tasks, return_exceptions=True)
    33. except asyncio.TimeoutError: # These only happen if return_exceptions is False
    34. print('Timeout') # With the default times, cancellation occurs first
    35. except asyncio.CancelledError:
    36. print('Cancelled')
    37. print('Result: ', res)
    38. asyncio.run(main())