← Learning Hub
Beginner

Async Code and the Event Loop

Node runs your JavaScript on one thread. Slow work like reading files or waiting for a database doesn't block it: Node starts the work, carries on, and runs your callback when the result is ready. This is the event loop.

Node handles many tasks with a single thread by never waiting idly: it starts slow work (files, network, timers), carries on, and runs your callback when the result is ready. Understanding this event loop explains why code runs in the order it does, and why one long calculation can freeze a server.

Example
You can edit this code.

Even a 0 ms timer waits until the current code has finished. Promise callbacks run before timers.

Callbacks, promises and async/await

Example
You can edit this code.

Doing things in parallel

Example
You can edit this code.

EventEmitter

Many Node objects send events. You can make your own:

Example
You can edit this code.
Never run a long loop (like crunching a million rows) in a web server - while it runs, no other user gets an answer. Do heavy work in a background job or a worker thread.
Key points
  • Node runs JavaScript on one thread with an event loop.
  • Promises and async/await handle waiting.
  • Avoid long CPU-heavy loops in servers.

📝 Test yourself

1. What prints first: a setTimeout(…, 0) callback or the next console.log line?
2. What does Promise.all do?
3. Fill in the method that listens for an event:
shop.("order", handler);