Async Programming
Promises, async/await, and the event loop
Introduction
In this lesson, you'll learn about async programming in JavaScript. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Python, you're familiar with promises, async/await, and the event loop.
JavaScript has its own approach to promises, async/await, and the event loop, which we'll explore step by step.
The JavaScript Way
Let's see how JavaScript handles this concept. Here's a typical example:
// Promise-based fetch (built-in)
async function fetchData(url) {
const res = await fetch(url);
const data = await res.json();
return data;
}
async function main() {
// Sequential
const a = await fetchData("https://api.example.com/a");
// Parallel
const [b, c] = await Promise.all([
fetchData("https://api.example.com/b"),
fetchData("https://api.example.com/c"),
]);
}
main(); // event loop runs automatically in browser/NodeComparing to Python
Here's how you might have written similar code in Python:
import asyncio
import aiohttp
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return await resp.json()
async def main():
# Sequential
a = await fetch("https://api.example.com/a")
# Parallel
b, c = await asyncio.gather(
fetch("https://api.example.com/b"),
fetch("https://api.example.com/c"),
)
asyncio.run(main())You may be used to different syntax or behavior.
JavaScript's event loop runs automatically — no asyncio.run() needed
You may be used to different syntax or behavior.
fetch() is built-in (browser + Node 18+); Python needs aiohttp
You may be used to different syntax or behavior.
Promise.all() ≈ asyncio.gather()
You may be used to different syntax or behavior.
Promise chaining (.then/.catch) has no Python equivalent
Step-by-Step Breakdown
1. async/await
The syntax is nearly identical. The big difference is JavaScript's event loop runs automatically.
async def fn():
result = await coro()
asyncio.run(fn())async function fn() {
const result = await promise();
}
fn(); // no run() needed2. Parallel Execution
Promise.all() is JavaScript's asyncio.gather() — both run coroutines/promises concurrently.
a, b = await asyncio.gather(coro1(), coro2())const [a, b] = await Promise.all([promise1(), promise2()]);3. Error Handling
Use try/catch with async/await in both languages.
try:
data = await fetch(url)
except aiohttp.ClientError as e:
print(e)try {
const data = await fetchData(url);
} catch (err) {
console.error(err);
}Common Mistakes
When coming from Python, developers often make these mistakes:
- JavaScript's event loop runs automatically — no asyncio.run() needed
- fetch() is built-in (browser + Node 18+); Python needs aiohttp
- Promise.all() ≈ asyncio.gather()
Key Takeaways
- No asyncio.run() — JS event loop is always running
- Promise.all() ≈ asyncio.gather()
- try/catch works the same for async errors