await用法:
await + 可等待对象
可等待对象:协程对象,Future,Task对象,IO等待
await在等待过程中会切换到其他任务中执行,await完成之后才会往下继续执行之后的代码
例1:
1 2 3 4 5 6 7 8 9 10 |
import asyncio async def func(): #协程函数 print("-------start--------") response = await asyncio.sleep(1) #可以获取await执行的值 print(response) print("-------end--------") asyncio.run(func()) |
例2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import asyncio async def func2(): print("-------func2_start--------") print("in func2") print("-------func2_end--------") return "func2的返回值" async def func1(): #协程函数 print("-------func1_start--------") response = await func2() #await可以跟协程对象 print(response) print("-------func1_end--------") asyncio.run(func1()) |

例3:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import asyncio async def func2(): print("-------func2_start--------") print("in func2") print("-------func2_end--------") return "func2的返回值" async def func1(): #await可以在协程函数里面有多个 print("-------func1_start--------") response1 = await func2() print(response1) response2 = await func2() print(response2) print("-------func1_end--------") asyncio.run(func1()) |

注:await就是等待对象的值得到结果之后再继续往下走,即下一步依赖上一步的结果的时候使用await,但是在等待过程中还是会切换到其他代码进行执行