Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

async and await in Node.js

In JavaScript, async and await make asynchronous code easier to read and understand. They allow us to write Promise-based code in a style that looks similar to normal sequential code.


1. What are async and await?

The async and await keywords are used to work with Promises in JavaScript.

  • async is used to declare an asynchronous function.
  • await pauses that async function until a Promise settles.
  • After the Promise fulfills, await gives us its result.
  • If the Promise rejects, the error can be handled using try...catch.
Simple Trick: async means the function works with asynchronous results. await means wait for the Promise's result inside that async function.

Example: At CIIT Training Institute, Samadhan requests course details from Pradnya. Instead of processing the result immediately, the program can await the Promise and then display the details.

2. Understanding async

The async keyword declares an asynchronous function. An async function always returns a Promise.

JavaScript
async function greet() {
    return "Welcome to CIIT Training Institute!";
}

greet().then((message) => {
    console.log(message);
});
Output
Welcome to CIIT Training Institute!
Explanation
  • async function greet() declares an async function.
  • The function returns a string.
  • JavaScript makes that returned value the fulfillment value of a Promise.
  • .then() receives the fulfilled value and displays it.
Remember: Even when an async function returns a normal value, the function itself returns a Promise.

3. Understanding await

The await keyword waits for a Promise to settle before continuing the async function. When the Promise fulfills, await produces its result.

JavaScript
function getCourse() {
    return Promise.resolve("Node.js");
}

async function displayCourse() {
    let course = await getCourse();

    console.log("Course Name: " + course);
}

displayCourse();
Output
Course Name: Node.js
Explanation
  • getCourse() returns a fulfilled Promise.
  • await getCourse() obtains the Promise's result.
  • The result is stored in the course variable.
  • The course name is displayed using console.log().

4. Flow of async and await

Async/Await Flow Diagram
Start Program
↓
Call async Function
The function returns a Promise.
↓
Encounter await
The async function waits for the Promise's result.
↓
Promise Fulfilled
Continue with the result.
Promise Rejected
Handle the error using try...catch.
Important: Await pauses the execution of the surrounding async function, not the entire JavaScript program. Other work can continue while the Promise is pending.

5. Practical Example

Samadhan wants to know whether Pradnya has completed a course report at CIIT Training Institute. The function returns a Promise, and Samadhan waits for the result before displaying the message.

JavaScript
function getReport() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve("Pradnya completed the course report.");
        }, 2000);
    });
}

async function showReport() {
    console.log("Samadhan is waiting for the report...");

    let report = await getReport();

    console.log(report);
    console.log("Samadhan received the report.");
}

showReport();
Output
Samadhan is waiting for the report...
Pradnya completed the course report.
Samadhan received the report.
The report message appears after approximately 2 seconds.
Step-by-step explanation
  1. getReport() creates and returns a Promise.
  2. setTimeout() schedules the report result after about two seconds.
  3. showReport() displays the waiting message.
  4. await getReport() waits for the report Promise within the async function.
  5. When the Promise fulfills, the report is displayed.
  6. The final message confirms that Samadhan received the report.

6. Error Handling using try...catch

Sometimes an asynchronous operation fails. We can use try...catch with await to handle a rejected Promise and prevent the error from going unhandled.

JavaScript
function getCourseResult() {
    return Promise.reject("Course result is not available.");
}

async function displayResult() {
    try {
        let result = await getCourseResult();
        console.log(result);
    } catch (error) {
        console.log("Error: " + error);
    }
}

displayResult();
Output
Error: Course result is not available.
Explanation
  • getCourseResult() returns a rejected Promise.
  • The rejection is thrown at the await expression.
  • The catch block receives the error.
  • The error message is displayed instead of leaving the rejection unhandled.

7. Using finally with async and await

The finally block executes after the try/catch flow, whether the operation succeeds or fails. It is useful for cleanup tasks such as hiding a loading indicator.

JavaScript
async function processAdmission() {
    try {
        let message = await Promise.resolve(
            "Samadhan's admission is confirmed."
        );

        console.log(message);
    } catch (error) {
        console.log("Error: " + error);
    } finally {
        console.log("Admission process completed.");
    }
}

processAdmission();
Output
Samadhan's admission is confirmed.
Admission process completed.

8. Sequential Execution with await

When multiple operations depend on one another, we can await each operation in sequence.

JavaScript
function getStudent() {
    return Promise.resolve("Pradnya");
}

function getStudentCourse(student) {
    return Promise.resolve(student + " is learning Node.js.");
}

async function displayStudentDetails() {
    let student = await getStudent();
    console.log("Student: " + student);

    let course = await getStudentCourse(student);
    console.log(course);
}

displayStudentDetails();
Output
Student: Pradnya
Pradnya is learning Node.js.

Here, the program waits for the student name first. It then passes that name to the second function and waits for the course information.

9. Difference between Promises and async/await

Promises async/await
Often uses .then() and .catch(). Uses await and commonly try...catch.
Can use method chaining to process results. Can make sequential asynchronous logic easier to read.
Promise-based asynchronous approach. Syntax built on top of Promises.
Error handling can be done with .catch(). Error handling can be done with try...catch.

10. Common Mistakes

Mistake Correct Approach
Using await in an ordinary function. Use it inside an async function, or at supported top-level module scope.
Assuming an async function returns a plain value. An async function always returns a Promise.
Ignoring a possible rejection. Handle errors using try...catch or a Promise rejection handler.
Awaiting independent operations one after another unnecessarily. Consider Promise.all() when the operations can safely run concurrently.

11. Important Points to Remember

  • async declares an asynchronous function.
  • An async function always returns a Promise.
  • await obtains a fulfilled Promise's result.
  • A rejected Promise can be handled using try...catch.
  • finally is useful for cleanup after success or failure.
  • Await pauses the current async function, not the entire program.
  • async/await makes many asynchronous workflows easier to read.

Summary

In this lesson, we learned how to declare async functions, use await with Promises, handle errors using try...catch, execute cleanup code using finally, and process dependent asynchronous operations in sequence. Examples involving Samadhan, Pradnya, and CIIT Training Institute demonstrate practical uses of async and await in JavaScript.