You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python asyncio中为何需使用双重await?请求技术解析

为什么这里需要双重await?

咱们拆解下代码里的关键逻辑,就能明白为啥要写两次await:

  • async函数的调用规则:page()是async函数,调用它的时候不会立刻执行函数体,只会返回一个协程对象,必须用await才能触发函数执行并拿到它的返回值。
  • asyncio.gather的返回值:page函数内部返回的是asyncio.gather()的结果,但asyncio.gather本身返回的是一个可等待对象(Future)——这个对象还得再用await一次,才能拿到10个work任务跑完后的结果列表。

所以原代码里的await (await page())其实是分两步:

  1. 第一次await page():执行page函数的逻辑,拿到它返回的gather生成的可等待对象
  2. 第二次await:等待这个gather对象完成,最终拿到结果列表

优化方案

完全没必要写双重await,直接在page函数内部把gather的结果await掉就行:

async def page():
    # 直接await gather,返回最终的结果列表
    return await asyncio.gather(*[
        work()
        for _ in range(10)
    ])

修改后run函数里只需要一次await:

async def run():
    results = await page()
    return max(results)  # gather返回的本来就是列表,不用转list

原代码的等价写法

你也可以把双重await拆成两行,逻辑更清晰:

async def run():
    gather_task = await page()  # 拿到gather的可等待对象
    results = await gather_task  # 等待gather完成,拿结果
    return max(list(results))

内容的提问来源于stack exchange,提问作者remi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 11:45:36