Concurrency and async · Part 22 of 36

The event loop, promises and async/await

Expert 18 min

How JavaScript and Python’s asyncio run many waiting tasks on one thread, and how to use async/await correctly.

What you will learn

  • You can explain the event loop, the task queue and microtasks.
  • You can write async code with promises/async-await and asyncio.
  • You can avoid blocking the loop and run tasks concurrently.

Before this: HTTP: how browsers and servers talk

Concurrency is not parallelism

Concurrency means several tasks are in progress at the same time — they take turns. Parallelism means they literally run at the same instant on different cores. A web server waiting on 1,000 slow clients needs concurrency, not 1,000 cores.

One robot cook taking tickets from a round conveyor while pots simmer on their own

The event loop

JavaScript runs your code on one thread. Long waits — timers, network, files — are handed to the runtime, which calls you back later. The event loop is the scheduler:

  1. Run the current task (a script, an event handler, a timer callback) to completion.
  2. Run all queued microtasks (promise reactions).
  3. Let the browser render, then take the next task from the task queue.
console.log("A");
setTimeout(() => console.log("B"), 0);      // task
Promise.resolve().then(() => console.log("C")); // microtask
console.log("D");
// prints A, D, C, B

Because nothing runs in between, a task that computes for two seconds blocks everything: no clicks, no rendering. Heavy work belongs in a Web Worker (or a worker thread in Node.js).

Promises and async/await

A promise is a placeholder for a value that arrives later; it is pending, then fulfilled or rejected. async/await lets you write promise code that reads top to bottom:

async function loadBeds() {
  const res = await fetch("/beds.json");   // pauses this function, not the thread
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

Python's asyncio uses the same model with coroutines:

import asyncio
async def fetch_bed(name):
    await asyncio.sleep(1)          # stands in for network I/O
    return name.upper()

async def main():
    async with asyncio.TaskGroup() as tg:   # Python 3.11+
        a = tg.create_task(fetch_bed("north"))
        b = tg.create_task(fetch_bed("south"))
    print(a.result(), b.result())  # after about 1 s, not 2

asyncio.run(main())

Sequential vs concurrent awaits

A common mistake is awaiting in a loop when the requests are independent:

for (const id of ids) results.push(await load(id));        // one after another
const results2 = await Promise.all(ids.map((id) => load(id))); // all at once

Promise.all rejects as soon as one fails; Promise.allSettled waits for all and reports each outcome. Limit concurrency when calling other people's servers (e.g. five at a time) to avoid overload and rate limits.

Cancellation and timeouts

Every network call needs a timeout. In JavaScript, pass an AbortSignal — fetch(url, { signal: AbortSignal.timeout(5000) }). In Python, wrap awaits in asyncio.timeout(5) (3.11+). Structured concurrency — task groups that own their child tasks and cancel the rest if one fails — keeps tasks from leaking; Python's TaskGroup (3.11, 2022) is an example.

Async all the way

An async function returns a promise/coroutine, so its callers must await it too — async spreads upwards ("function colouring"). Never call blocking functions (a synchronous time.sleep, a CPU-heavy loop, synchronous file reads in a server) inside async code; they freeze the whole loop.

Try it: JavaScript sandbox

Write and run small JavaScript programs; the checker tells you when an exercise is solved.

Turn on JavaScript to use this lab. Worked example:

Exercise 13: delay(ms, value) returns a promise. Start three delays of 300 ms concurrently with Promise.all and print their values in one array. The checker also confirms that the whole run took well under 900 ms.

Key points

  • Concurrency = tasks in progress together; parallelism = running at the same instant.
  • JavaScript and asyncio run one task at a time; the event loop runs tasks, then microtasks.
  • await pauses the function, not the thread; blocking code freezes everything.
  • Use Promise.all/allSettled or TaskGroup for independent work; add timeouts and limits.
  • Structured concurrency ties child tasks to a scope so they cannot leak.

Flashcards

Question: In which order do A, D, C, B print in the event-loop example — and why?
Answer: A, D (synchronous), C (microtask), B (task) — microtasks run before the next task.
Question: What happens if an event handler computes for 2 seconds?
Answer: The page freezes: no rendering or input until it finishes.
Question: Promise.all vs Promise.allSettled?
Answer: all rejects on the first failure; allSettled waits for every result.
Question: What does asyncio.TaskGroup add?
Answer: Structured concurrency: it waits for its tasks and cancels the rest if one fails.

Check yourself

Think about your answer, then open it. In the app the quiz is interactive, earns points and brings back what you missed.

  1. In which order does the example print?

    Show the answer

    A → D → C → B

    Synchronous code first, then microtasks (promise), then the timer task.

    Source: HTML Living Standard, Event loops

  2. Ten independent requests each take 1 s. How long does await Promise.all(...) take, roughly?

    • About 1 s
    • About 10 s
    • About 0.1 s
    • It depends on the number of cores only
    Show the answer

    About 1 s

    They wait concurrently, so total ≈ the slowest one.

    Source: MDN, Promise.all()

  3. Which calls block an asyncio event loop?

    • time.sleep(2)
    • A CPU-heavy loop over 10 million items
    • await asyncio.sleep(2)
    • Synchronous file reading of a big file
    Show the answer

    time.sleep(2); A CPU-heavy loop over 10 million items; Synchronous file reading of a big file

    Only the awaited asyncio.sleep yields to the loop.

    Source: Python docs, asyncio — Developing with asyncio

  4. In JavaScript, fetch(url, { signal: AbortSignal.___(5000) }) aborts after 5 s.

    Show the answer

    timeout

    AbortSignal.timeout(ms) creates a signal that aborts after ms milliseconds.

    Source: MDN, AbortSignal.timeout()

Sources

Facts checked on 2026-11-30. Skillgrove lessons are free learning material — no certificate and no accreditation.