"""
await关键字, await+(cortinue对象,future对象,task对象) 需要在等待的对象返回值以后,才能执行await之后的代码
await适用的场景时,await后面的代码会依赖 await等待的对象的返回值
"""
import asyncio
# 例1 await asyncio.sleep()
async def func(index):
print("开始执行func{}".format(index))
await asyncio.sleep(1)
print("运行结束{}".format(index))
# 例2 await+ cortinue对象
async def other(index):
print("other start {}".format(index))
await asyncio.sleep(2)
print("other end {}".format(index))
async def func2(index):
print("func2 start {}".format(index))
await other(index)
print("func2 end {}".format(index))
# 例3 依赖await 返回值的
async def func3(index):
print("func3 start {}".format(index))
answer = await add(index)
print("func3 end {}".format(answer))
async def add(index):
print("add start {}".format(index))
# await asyncio.sleep(2)
print("add end {}".format(index))
return 1+index
tasks = [ asyncio.ensure_future(func3(index)) for index in range(5)]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
执行结果:
func3 start 0
add start 0
add end 0
func3 end 1
func3 start 1
add start 1
add end 1
func3 end 2
func3 start 2
add start 2
add end 2
func3 end 3
func3 start 3
add start 3
add end 3
func3 end 4
func3 start 4
add start 4
add end 4
func3 end 5
Process finished with exit code 0