【问题标题】:Python: await the outer most async functionPython:等待最外面的异步函数
【发布时间】:2020-12-02 06:13:20
【问题描述】:

可以等待使用 'async' 关键字(Python 3.5+)创建的 Python 协程,但是,不能等待最外面的协程,因为 Python 说 “SyntaxError: 'await' outside function”

import asyncio as aio

async def f():
    print(1)
    await aio.sleep(3)
    print(2)
    return 3

print(await f())

如何“等待”上例中的“f”函数?

【问题讨论】:

    标签: python promise async-await python-asyncio coroutine


    【解决方案1】:

    如果你使用 Python 3.7+,语法更简单(无需手动创建循环等):

    import asyncio as aio
    
    async def f():
        print(1)
        await aio.sleep(3)
        print(2)
        return 3
    
    print(aio.run(f())
    

    【讨论】:

      【解决方案2】:

      不可能在全局范围内等待,而是运行一个事件循环,如下所示:

      import asyncio as aio
      
      async def f():
          print(1)
          await aio.sleep(3)
          print(2)
          return 3
      
      def fdone(r):
          print(r.result())
      
      loop = aio.get_event_loop()
      t = loop.create_task(f())
      t.add_done_callback(fdone)
      loop.run_until_complete(t)
      print(4)
      

      【讨论】:

      • 更简单的print(loop.run_until_complete(f())) 也可以,因为run_until_complete() 会自动创建任务。您不需要add_done_callback,因为run_until_complete() 返回它收到的等待结果。
      猜你喜欢
      • 2021-01-13
      • 2023-03-13
      • 1970-01-01
      • 2021-10-22
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多