Asynchronous Programming in Node.js
Learn how asynchronous programming works in Node.js, how non-blocking operations improve application responsiveness, and how callbacks, Promises, and async/await handle asynchronous tasks.
In the previous module, we learned about events and EventEmitter. Now, we will explore asynchronous programming in Node.js. Asynchronous programming allows an application to start an operation and continue executing other code while waiting for that operation to complete.
Throughout this module, we will use examples from CIIT Training Institute. Samadhan and Pradnya will help us understand how an application can handle student enquiries, course information, and other tasks without unnecessarily blocking execution.
1. What Is Asynchronous Programming?
Asynchronous programming is a programming approach in which certain operations can complete later without requiring the rest of the program to wait synchronously for their results.
For example, when Samadhan requests student information from a database, the application may need to wait for the database response. With asynchronous APIs, Node.js can continue handling other work while the operation is in progress.
When the result becomes available, the application can process it using a callback, a Promise, or async/await.
2. Synchronous vs Asynchronous Programming
In synchronous execution, the next statement generally waits for the current operation to finish. With asynchronous APIs, an operation can complete later while other eligible code runs.
| Feature | Synchronous | Asynchronous |
|---|---|---|
| Execution | Statements proceed after the current operation finishes. | Some operations complete later. |
| Waiting | A blocking operation can prevent further execution. | Non-blocking operations allow other work to proceed. |
| Result handling | The result is available before execution continues. | The result is handled later using an asynchronous mechanism. |
| Node.js example | readFileSync() |
readFile() with a callback. |
3. Example of Synchronous Execution
First, let's understand a simple synchronous program. Each statement executes in sequence.
Program
console.log("Samadhan started the task.");
console.log("Pradnya is checking course details.");
console.log("Task completed.");
Expected Output
Samadhan started the task.
Pradnya is checking course details.
Task completed.
Each console.log() statement executes in order.
This example is synchronous because no asynchronous operation
is involved.
4. Example of Asynchronous Execution
Node.js provides functions such as setTimeout()
that schedule a callback to run later. This helps demonstrate
how execution can continue before a scheduled callback runs.
Program
console.log("Samadhan started the task.");
setTimeout(() => {
console.log("Pradnya finished checking course details.");
}, 2000);
console.log("Samadhan continues other work.");
Expected Output
Samadhan started the task.
Samadhan continues other work.
Pradnya finished checking course details.
The callback passed to setTimeout() is scheduled
to run after at least approximately two seconds. Meanwhile,
the next synchronous statement executes.
5. Asynchronous Execution Flow
This diagram shows how Node.js can continue executing synchronous code while a callback is waiting to run.
1. Start Program
Samadhan starts the task.
2. Schedule Asynchronous Work
setTimeout(callback, 2000)
3. Continue Synchronous Code
Samadhan continues other work.
4. Execute Scheduled Callback
Pradnya's completion message appears.
Note: The delay specifies a minimum scheduling threshold, not an exact execution time. The callback runs when the event loop can process it.
6. Why Is Asynchronous Programming Important in Node.js?
Node.js is commonly used for applications that handle network requests, file operations, database queries, and other input/output tasks. Non-blocking APIs help an application remain responsive while these operations are in progress.
| Operation | Example at CIIT Training Institute | Possible Benefit |
|---|---|---|
| File operations | Reading course information from a file. | Other work can continue while asynchronous file I/O is pending. |
| Database operations | Retrieving student enquiry details. | Requests can be handled without synchronously waiting for every query. |
| HTTP requests | Serving multiple student enquiries. | Non-blocking I/O supports responsive request handling. |
| Timers | Scheduling a delayed notification. | Other eligible code can run while the timer is pending. |
7. Common Asynchronous Programming Patterns
JavaScript and Node.js provide several ways to handle asynchronous results. We will study each approach in detail in the upcoming lessons.
| Pattern | How It Works | Common Example |
|---|---|---|
| Callbacks | A function is passed to be called later. | fs.readFile() |
| Promises | Represent the eventual success or failure of an operation. | fetch() |
| async/await | Provides syntax for working with Promises. | await fetch(url) |
| Timers | Schedule callbacks for later execution. | setTimeout() |
8. Introduction to Callbacks
A callback is a function passed as an argument to another function. The receiving function can call that callback when a particular task or condition is reached.
Callbacks can be synchronous or asynchronous. In Node.js, callback functions are commonly used to process the result of asynchronous operations.
Example
function greetStudent(name, callback) {
console.log("Welcome, " + name);
callback();
}
function showInstitute() {
console.log("Welcome to CIIT Training Institute!");
}
greetStudent("Pradnya", showInstitute);
Expected Output
Welcome, Pradnya
Welcome to CIIT Training Institute!
In this example, showInstitute is passed as
a callback function. The greetStudent() function
invokes it after displaying the student's name.
9. Asynchronous Programming Concepts Diagram
This diagram summarizes the main patterns we will learn throughout the asynchronous programming module.
Asynchronous Operation
Example: Read course information
Callbacks
Handle a result through a function.
Promises
Represent a future result or failure.
async/await
Work with Promises using readable syntax.
Important Points
- Asynchronous programming allows certain operations to complete later.
- Non-blocking operations allow other eligible work to proceed while I/O is pending.
- Node.js provides callback-based and Promise-based APIs.
-
async/awaitprovides syntax for working with Promises. - Callbacks can be synchronous or asynchronous.
-
setTimeout()schedules a callback; it does not guarantee execution at an exact time.
Summary
In this lesson, we introduced asynchronous programming in Node.js and compared synchronous and asynchronous execution. We learned how scheduled callbacks allow synchronous code to continue, explored why non-blocking I/O matters, and introduced callbacks, Promises, and async/await. In the next lesson, we will study callbacks in more detail using practical JavaScript examples.