```python
import asyncio
import time
from typing import Callable, Any
# 回调地狱版本
def callback_hell_example():
传统回调地狱的实现方式
def fetch_data_from_db(query: str, callback: Callable):
模拟数据库查询
print(f开始查询: {query})
time.sleep(1) # 模拟IO阻塞
callback(f查询结果: {query})
def process_data(data: str, callback: Callable):
处理数据
print(f处理数据: {data})
time.sleep(0.5)
callback(f已处理 {data})
def save_to_file(result: str, callback: Callable):
保存到文件
print(f保存结果: {result})
time.sleep(0.3)
callback(f已保存 {result})
# 回调地狱 - 嵌套的回调函数
def start_process():
fetch_data_from_db(SELECT FROM users,
lambda db_result: process_data(db_result,
lambda processed_result: save_to_file(processed_result,
lambda final_result: print(f最终结果: {final_result})
)
)
)
start_process()
# 使用asyncio和async/await的优雅版本
async def async_elegant_example():
使用async/await的优雅实现
async def fetch_data_from_db(query: str) -> str:
异步数据库查询
print(f开始查询: {query})
await asyncio.sleep(1) # 异步等待
return f查询结果: {query}
async def process_data(data: str) -> str:
异步处理数据
print(f处理数据: {data})
await asyncio.sleep(0.5)
return f已处理 {data}
async def save_to_file(result: str) -> str:
异步保存到文件
print(f保存结果: {result})
await asyncio.sleep(0.3)
return f已保存 {result}
# 使用async/await的线性代码
async def start_async_process():
db_result = await fetch_data_from_db(SELECT FROM users)
processed_result = await process_data(db_result)
final_result = await save_to_file(processed_result)
print(f最终结果: {final_result})
await start_async_process()
# 并发执行的优化版本
async def concurrent_async_example():
并发执行的异步版本
async def fetch_user_data():
await asyncio.sleep(1)
return 用户数据
async def fetch_product_data():
await asyncio.sleep(1.2)
return 产品数据
async def fetch_order_data():
await asyncio.sleep(0.8)
return 订单数据
# 并发执行多个异步任务
async def gather_all_data():
# 使用asyncio.gather并发执行
results = await asyncio.gather(
fetch_user_data(),
fetch_product_data(),
fetch_order_data(),
return_exceptions=True
)
for i, result in enumerate(results, 1):
print(f结果 {i}: {result})
return results
return await gather_all_data()
# 错误处理对比
def callback_error_handling():
回调方式的错误处理(复杂)
def operation(callback, error_callback):
try:
# 模拟可能失败的操作
result = 操作成功
callback(result)
except Exception as e:
error_callback(e)
def on_success(result):
print(f成功: {result})
def on_error(error):
print(f错误: {error})
operation(on_success, on_error)
async def async_error_handling():
async/await的错误处理(简洁)
async def async_operation():
# 模拟异步操作
await asyncio.sleep(1)
return 操作成功
# 如果要模拟错误,可以取消下面的注释
# raise ValueError(模拟错误)
try:
result = await async_operation()
print(f成功: {result})
except Exception as e:
print(f错误: {e})
# 性能对比演示
async def performance_comparison():
性能对比演示
async def async_task(name: str, delay: float):
await asyncio.sleep(delay)
return f{name} 完成
# 串行执行
start_time = time.time()
# 传统方式(伪代码表示)
# 需要等待每个任务完成才能开始下一个
# 异步并发方式
tasks = [
async_task(任务1, 1),
async_task(任务2, 1),
async_task(任务3, 1)
]
results = await asyncio.gather(tasks)
end_time = time.time()
print(f并发执行时间: {end_time - start_time:.2f}秒)
print(f结果: {results})
# 实际应用示例
class AsyncDataProcessor:
异步数据处理器
def __init__(self):
self.semaphore = asyncio.Semaphore(5) # 限制并发数
async def process_item(self, item: str):
处理单个项目
async with self.semaphore:
# 模拟异步处理
await asyncio.sleep(0.1)
return f处理后的 {item}
async def process_batch(self, items: list):
批量处理
tasks = [self.process_item(item) for item in items]
return await asyncio.gather(tasks)
# 主函数演示
async def main():
print(=== 回调地狱示例 ===)
callback_hell_example()
print( === Async/Await优雅示例 ===)
await async_elegant_example()
print( === 并发执行示例 ===)
await concurrent_async_example()
print( === 错误处理对比 ===)
callback_error_handling()
await async_error_handling()
print( === 性能对比 ===)
await performance_comparison()
print( === 实际应用示例 ===)
processor = AsyncDataProcessor()
items = [f项目{i} for i in range(10)]
results = await processor.process_batch(items)
print(f批量处理结果: {results})
if __name__ == __main__:
asyncio.run(main())
```
这段代码展示了Python异步编程从回调地狱到async/await的优雅进化:
回调地狱的问题:
- 深度嵌套的回调函数
- 错误处理复杂
- 代码可读性差
- 难以维护和调试
async/await的优势:
- 线性代码结构,类似同步编程
- 简洁的错误处理(try/except)
- 更好的可读性和可维护性
- 内置并发支持(asyncio.gather)
- 资源管理(Semaphore等)
关键改进点:
1. 使用`async def`定义异步函数
2. 使用`await`代替回调
3. `asyncio.gather`实现并发执行
4. 标准的try/except错误处理
5. 使用Semaphore控制并发数量
这种进化让异步代码更加直观、易于理解和维护,同时保持了高性能的特性。

被折叠的 条评论
为什么被折叠?



