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"),
]);
1οΈβ£ Requests start immediately
const p1 = fetch("/a");
const p2 = fetch("/b");
const p3 = fetch("/c");
- 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
π§ 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(),
]);
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)