async/await 误用主要表现为:未用 await 调用协程、在同步上下文(如 Flask 视图或脚本顶层)直接调用 async 函数而不启动事件循环、gather 传入函数而非协程对象、忽略异常传播策略、create_task 后未 await、await 用于 CPU 密集型操作导致事件循环阻塞,以及混用同步/异步上下文管理器和迭代器。

混淆 async/await 和普通函数调用
很多人写完 async def 函数,却忘了用 await 调用它,结果得到一个 coroutine 对象而不是实际结果。比如:
-
result = fetch_data()→ 返回 coroutine,不会执行 -
result = await fetch_data()→ 正确等待并获取返回值
更隐蔽的问题是,在非 async 函数里直接调用 async 函数(没 await、也没用 asyncio.run()),程序会静默“跳过”异步逻辑,还可能引发 RuntimeWarning: coroutine 'xxx' was never awaited。
在同步上下文中错误地使用异步代码
常见于 Web 框架(如 Flask、Django 默认视图)或脚本顶层:直接调用 async 函数却不启动事件循环。例如:
- Flask 视图里写
await db.query(...)→ 报错RuntimeError: no running event loop - 想在普通 Python 脚本中测试异步函数,只写
main()不加asyncio.run(main())
解决方法:确保 async 函数总在事件循环中运行;框架不原生支持 asyncio 的,需换用 FastAPI、Starlette,或用 asyncio.run_in_executor 包装阻塞调用。
立即学习“Python免费学习笔记(深入)”;
误用 asyncio.gather / asyncio.create_task 导致并发失控
gather 是并发执行多个协程的常用方式,但容易忽略两点:
- 传入的是协程对象(
awaitable),不是已执行的 task;写成gather(f(), g())是对的,但gather(f, g)(没加括号)就传了函数对象,会报错 - 所有任务共享同一个异常策略:任一失败,
gather默认立刻取消其余任务。需要“容错并发”,得加return_exceptions=True
另外,用 create_task 后忘记 await 对应的 task,会导致任务被调度但结果丢失,甚至因未 await 引发警告。
以为 await 就等于“不阻塞”,忽略了 CPU 密集型操作
await 只让出控制权给事件循环,适用于 I/O 等待(网络、磁盘、数据库)。但如果你在 async 函数里写了个大循环或复杂计算:
-
for i in range(10**7): total += i→ 会完全阻塞事件循环,其他协程无法运行 - 正确做法:用
loop.run_in_executor把 CPU 工作扔进线程池,再 await 结果
async 不是万能加速器,它解决的是 I/O 等待的并发效率,不是替代多进程或多线程做计算密集任务。
忽视异步上下文管理器和迭代器的正确用法
async 版本的资源管理必须配对使用:async with 和 async for,不能混用同步语法:
- ❌
with aiohttp.ClientSession() as session:→ 类型错误,session 是 async context manager - ✅
async with aiohttp.ClientSession() as session: - ❌
for chunk in response.content:→ content 是 async iterator - ✅
async for chunk in response.content:
漏掉 async 关键字,轻则报 TypeError,重则资源泄漏(比如连接没关闭)。










