Async Programming
Handling asynchronous operations
Introduction
In this lesson, you'll learn about async programming in Python. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with handling asynchronous operations.
Python has its own approach to handling asynchronous operations, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
import asyncio
import aiohttp
# async/await
async def get_data(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.json()
# Parallel execution
async def main():
a, b = await asyncio.gather(
get_data("https://api.example.com/a"),
get_data("https://api.example.com/b"),
)
print(a, b)
# Run the event loop
asyncio.run(main())Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
// Promises
fetch("https://api.example.com/data")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
// async/await
async function getData(url) {
try {
const res = await fetch(url);
const data = await res.json();
return data;
} catch (err) {
console.error(err);
}
}
// Parallel execution
const [a, b] = await Promise.all([
fetch("/api/a").then(r => r.json()),
fetch("/api/b").then(r => r.json()),
]);You may be used to different syntax or behavior.
Python requires asyncio.run() to start the event loop
You may be used to different syntax or behavior.
asyncio.gather() ≈ Promise.all()
You may be used to different syntax or behavior.
Use aiohttp (not requests) for async HTTP
You may be used to different syntax or behavior.
async with for async context managers
Step-by-Step Breakdown
1. async/await Syntax
Python async/await looks almost identical to JavaScript. The key difference is you need asyncio.run() to execute async code.
async function fn() { return await fetch(url); }async def fn():
return await some_coroutine()2. Parallel Tasks
asyncio.gather() runs multiple coroutines concurrently, similar to Promise.all().
const [a, b] = await Promise.all([fa(), fb()]);a, b = await asyncio.gather(fa(), fb())3. Running Async Code
In Python you must explicitly start an event loop. asyncio.run() is the standard way.
// In Node.js top-level await is supportedasyncio.run(main()) # start the event loopCommon Mistakes
When coming from JavaScript, developers often make these mistakes:
- Python requires asyncio.run() to start the event loop
- asyncio.gather() ≈ Promise.all()
- Use aiohttp (not requests) for async HTTP
Key Takeaways
- async def and await work like JavaScript
- asyncio.gather() for concurrent tasks
- asyncio.run(main()) to start execution