以下代码主要包含两个函数,main()和other_function()。main()函数先打印“A”,然后睡眠1秒,在它睡眠的同时,执行other_function()函数,打印“1”。然后other_function()函数睡眠2秒,在它睡眠的同时,执行main()函数,打印“B”。最后执行other_function()函数,打印“2”。
import asyncio
async def main():
task = asyncio.create_task(other_function())
print("A")
await asyncio.sleep(1)
print("B")
await task
async def other_function():
print("1")
await asyncio.sleep(2)
print("2")
await main()
如何处理返回值
import asyncio
async def main():
task = asyncio.create_task(other_function())
print("A")
await asyncio.sleep(1)
print("B")
return_value = await task
print(f'Return value was {return_value}')
async def other_function():
print("1")
await asyncio.sleep(2)
print("2")
return 10
await main()