← Back to Articles

Async

Comparison between JavaScript and Python

The information comes from the Udemy course "Become an AI Engineer: Python for JavaScript Developers" by Vilva Athiban

Feature JavaScript Python
async / await
async function fn(bookId) {
  await new Promise((resolve) => setTimeout(resolve, 1000));
  return { title: "dummy" };
}

async function main() {
  const book1 = await fn(1);
  console.log(book1.title);
}

main();
asyncio.run()
import asyncio
import requests 

# --- mimic a 1s API call with asyncio.sleep ---
async def fn(book_id):
    await asyncio.sleep(1) # like setTimeout 
    return {"title": "dummy"}

# --- A main() that awaits it ---
async def main():
    book1 = await fn(1)
    print(book1["title"])


asyncio.run(main()) # <-- starts the event loop
A real HTTP call
import axios from "axios";
async function getData() {
  const response = await axios.get("https://api.example.com/data");
  console.log(response.status); // 200
  console.log(response.data);// parsed JSON
  // axios also has .post / .put / .patch / .delete 
}
def get_data():
    response = requests.get("https://api.example.com/data")
    print(response.status_code)     # 200
    print(response.json())          # parsed JSON body
    # requests also has .post / .put / .patch / .delete