Premium lesson

Asynchronous Execution in Node.js

Node.js·4 min read·Jan 1, 2025

JavaScript is by design single-threaded, which means that each instruction is executed one after the other, in a sequence.

This synchronous behaviour, referred to as blocking, implies that JavaScript will wait for each task to complete before executing the next one.

While desirable in most cases, this sometimes leads to performance issues when it comes to handling time-consuming or concurrent tasks, like reading very large files or handling hundreds of incoming network requests.

The event loop

In Node.js, the event loop is the mechanism that allows JavaScript to asynchronously run certain operations in the background without awaiting for their completion, thus allowing the program to run in a non-blocking manner.

When a potentially slow operation is initiated, such as an input/output or a network operation, Node.js automatically delegates it to the system and continues executing other code while it is being processed.

Once the operation is complete, Node.js then notifies the program through callbacks and events that allow it to handle the result or failure of the operation.

Here is a step-by-step overview of the event loop in Node.js:

  • Step 1: Executing synchronous code

    Node.js starts by sequentially executing the synchronous parts of the code, which includes variable declarations, function definitions, and any operations that don't require asynchronous behavior.

  • Step 2: Offloading asynchronous tasks

    When the program encounters asynchronous functions like setTimeout(), these tasks are offloaded to the system to be processed in the background, thus avoiding blocking the main execution thread.

  • Step 3: Entering the event loop

icon light bulb key

Unlock the Build CLI Apps in JavaScript & Node.js module

Learn how to build, integrate, and safeguard scalable CLI tools, scripts, and apps with JavaScript, Node.js, npm, and Git.

You get immediate access to:

  • 45 focused lessons across JavaScript, Node.js, npm, and Git
  • 17 real-world projects with commented solutions
  • Ongoing updates to this bundle
  • Lifetime access to this bundle
Unlock this module