DEV Community

Mohsen Fallahnejad
Mohsen Fallahnejad

Posted on Edited on Originally published at bitlyst.blog

How Promise.all Works in a Single-Threaded JavaScript World

How Promise.all Works in a Single-Threaded JavaScript World

If JavaScript is single-threaded, how can Promise.all() handle multiple requests at the same time?

The short answer:

JavaScript is single-threaded for executing code, but I/O is handled outside the JS thread.


🧠 What β€œsingle-threaded” really means

  • Only one piece of JavaScript runs at a time.
  • JS does NOT block while waiting for network, timers, or disk.

βš™οΈ Step-by-step: What happens with Promise.all

await Promise.all([
  fetch("/a"),
  fetch("/b"),
  fetch("/c"),
]);
Enter fullscreen mode Exit fullscreen mode

1️⃣ Requests start immediately

const p1 = fetch("/a");
const p2 = fetch("/b");
const p3 = fetch("/c");
Enter fullscreen mode Exit fullscreen mode
  • Promises are created instantly.
  • Network work starts in the background.
  • JS thread is free.

2️⃣ Network runs outside JS

  • Browser or Node runtime handles requests.
  • Requests run concurrently.
  • JS thread does nothing during this time.

3️⃣ Promise resolution uses microtasks

  • When a request finishes, its Promise resolves.
  • .then() callbacks go to the microtask queue.
  • JS executes them one by one.

4️⃣ Promise.all resolves last

  • Waits for all Promises to resolve.
  • Rejects early if one fails.

πŸ”„ Timeline

JS Thread: start A β†’ start B β†’ start C β†’ (free) β†’ run handlers
  β”œβ”€ Network: A request β†’ A done
  β”œβ”€ Network: B request β†’ B done
  └─ Network: C request β†’ C done
Enter fullscreen mode Exit fullscreen mode

🧠 Mental Model

  • JS thread = single chef
  • Network = multiple delivery drivers
  • Promise.all = wait for all deliveries

⚠️ Important note

Promise.all() does NOT make CPU work parallel.

Promise.all([
  heavyTask(),
  heavyTask(),
]);
Enter fullscreen mode Exit fullscreen mode

This still blocks the UI.


🧱 Browser vs Node

Layer Responsibility
JS Thread Executes callbacks
Browser APIs / libuv Async I/O
Promises Coordination

βœ… Summary

Concept Meaning
Single-threaded One JS execution at a time
Concurrent Multiple async ops in flight
Promise.all Waits for all async results
Parallel JS ❌
Parallel I/O βœ…

✨ Final takeaway

JS coordinates work β€” it doesn’t do it all itself.

Promise.all works because the heavy work happens outside the JS thread.


Originally published on Bitlyst.

Top comments (0)