【协程】4、await关键字

1、await

  • await + 可等待的对象(协程对象、Future、Task对象 --> IO等待)
  • 示例1:
import asyncio


async def func():
    print('来玩啊')
    response = await asyncio.sleep(2)
    print('结束:', response)


loop = asyncio.get_event_loop()
loop.run_until_complete(func())
  • 示例2:
# -*- coding: utf-8 -*-
import asyncio


async def other():
    print('start')
    await asyncio.sleep(2)
    print('end')
    return '返回值'


async def func():
    print('执行协程函数内部代码')
    # 遇到IO操作挂起当前协程(任务),等IO操作完成之后再继续往下执行,当前协程挂起时,事件循环可以去执行其他协程(任务)
    response = await other() # await就是等other()有返回值之后,才会继续往下执行
    print('IO请求结束,结果为:', response)
  • 示例3:
# -*- coding: utf-8 -*-
import asyncio


async def other():
    print('start')
    await asyncio.sleep(2)
    print('end')
    return '返回值'


async def func():
    print('执行协程函数内部代码')
    # 遇到IO操作挂起当前协程(任务),等IO操作完成之后再继续往下执行,当前协程挂起时,事件循环可以去执行其他协程(任务)
    response1 = await other() # await就是等other()有返回值之后,才会继续往下执行
    print('IO请求结束,结果为:', response1)
    
    response2 = await other() # await就是等other()有返回值之后,才会继续往下执行
    print('IO请求结束,结果为:', response2)
  • await就是等待对象的值得到结果之后再继续向下走
posted @ 2022-05-31 14:05  郭祺迦  阅读(124)  评论(0)    收藏  举报