JS
PY

JavaScript to Python

10 lessons

Progress0%
1Variables and Constants2Functions3Arrays vs Lists4Objects vs Dictionaries5Classes and OOP6Modules and Imports7Array Methods vs Comprehensions8Error Handling9Async Programming10File I/O
All Mirror Courses
JS
PY
Async Programming
MirrorLesson 9 of 10
Lesson 9

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.

Mirror Card
JS
From JavaScript:

In JavaScript, you're familiar with handling asynchronous operations.

PY
In Python:

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:

PY
Python 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:

JS
JavaScript (What you know)
// 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()),
]);
Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

Python requires asyncio.run() to start the event loop

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

asyncio.gather() ≈ Promise.all()

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

Use aiohttp (not requests) for async HTTP

Mirror Card
JS
From JavaScript:

You may be used to different syntax or behavior.

PY
In Python:

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.

JS
JavaScript
async function fn() { return await fetch(url); }
PY
Python
async def fn():
    return await some_coroutine()

2. Parallel Tasks

asyncio.gather() runs multiple coroutines concurrently, similar to Promise.all().

JS
JavaScript
const [a, b] = await Promise.all([fa(), fb()]);
PY
Python
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.

JS
JavaScript
// In Node.js top-level await is supported
PY
Python
asyncio.run(main())  # start the event loop
Common Pitfall
Don't call asyncio.run() inside an already-running event loop (e.g., Jupyter). Use await directly there.

Common 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
Common Pitfall
Don't assume Python works exactly like JavaScript. While the concepts may be similar, the syntax and behavior can differ significantly.

Key Takeaways

  • async def and await work like JavaScript
  • asyncio.gather() for concurrent tasks
  • asyncio.run(main()) to start execution
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your JavaScript code in Python to practice these concepts.
PreviousNext