DEV Community

niuniu
niuniu

Posted on

Quick Tip: Python Async/Await Basics

Quick Tip

Python async/await basics:

import asyncio

# Async function
async def fetch_data():
    print("Fetching data...")
    await asyncio.sleep(2)  # Simulate I/O
    return {"data": "Hello"}

# Run async function
async def main():
    result = await fetch_data()
    print(result)

# Run multiple tasks concurrently
async def main():
    tasks = [fetch_data() for _ in range(3)]
    results = await asyncio.gather(*tasks)
    print(results)

asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

Powered by MonkeyCode: https://monkeycode-ai.net/

python #async #tips

Top comments (0)