Skip to content
เข้าสู่ระบบ

Async Patterns

Patterns และ best practices สำหรับ asynchronous programming ใน Python

import asyncio
async def fetch_data(name, delay):
'''Simulate async operation'''
await asyncio.sleep(delay)
return f"Result from {name}"
async def main():
# Gather - run concurrent and wait for all
results = await asyncio.gather(
fetch_data("API 1", 0.1),
fetch_data("API 2", 0.15),
fetch_data("API 3", 0.1)
)
print(f"All results: {results}")
# Results are in order of tasks
# asyncio.run(main())
print("gather(): run all concurrent, wait for all, return in order")
print("""
Usage:
results = await asyncio.gather(coro1, coro2, coro3)
# With return_exceptions=True
# If one fails, others continue
results = await asyncio.gather(*tasks, return_exceptions=True)
for result in results:
if isinstance(result, Exception):
print(f"Error: {result}")
else:
print(f"Success: {result}")
""")

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด