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

Promises in Node.js

A Promise in JavaScript represents the eventual completion or failure of an asynchronous operation and its resulting value. Promises help us organize asynchronous code.


1. What is a Promise?

Imagine Samadhan asks Pradnya to prepare a course report at CIIT Training Institute. Pradnya may still be preparing it, may complete it successfully, or may fail to prepare it. A Promise represents this pending work and its eventual result.

Simple Trick: A Promise is like a commitment that a result will be available later, either successfully or with an error.
Promise Flow Diagram
Promise Created
↓
Pending
The operation is still in progress
↓
Fulfilled
Operation succeeded
Rejected
Operation failed

2. States of a Promise

State Meaning Example
Pending The operation has not completed yet. Pradnya is preparing the report.
Fulfilled The operation completed successfully. The report is ready.
Rejected The operation failed. The report could not be prepared.

A Promise starts in the pending state and settles as fulfilled or rejected. Once settled, its state does not change again.

3. Creating a Promise

We create a Promise using the new Promise() constructor. It receives an executor function with two important parameters: resolve and reject.

JavaScript
const coursePromise = new Promise((resolve, reject) => {
    let courseReady = true;

    if (courseReady) {
        resolve("Course details are ready!");
    } else {
        reject("Course details are not available.");
    }
});

coursePromise
    .then((message) => {
        console.log(message);
    })
    .catch((error) => {
        console.log(error);
    });
Output
Course details are ready!
Explanation
  • new Promise() creates a Promise.
  • resolve() fulfills the Promise with a value.
  • reject() rejects the Promise with a reason.
  • .then() handles fulfillment.
  • .catch() handles rejection.

4. Using then()

The then() method is used to handle a fulfilled Promise. Let's see an example with Samadhan and CIIT Training Institute.

JavaScript
const admissionPromise = new Promise((resolve) => {
    resolve("Samadhan's admission is confirmed at CIIT Training Institute.");
});

admissionPromise.then((message) => {
    console.log(message);
});
Output
Samadhan's admission is confirmed at CIIT Training Institute.

When the Promise is fulfilled, the callback passed to then() receives the resolved value.

5. Using catch()

The catch() method handles a rejected Promise.

JavaScript
const resultPromise = new Promise((resolve, reject) => {
    reject("Course registration failed.");
});

resultPromise
    .then((message) => {
        console.log(message);
    })
    .catch((error) => {
        console.log("Error: " + error);
    });
Output
Error: Course registration failed.

Because the Promise is rejected, the error handler in catch() runs instead of the fulfillment handler.

6. Using finally()

The finally() method runs after a Promise settles, whether it fulfills or rejects. It is useful for cleanup tasks.

JavaScript
const paymentPromise = Promise.resolve("Payment successful!");

paymentPromise
    .then((message) => {
        console.log(message);
    })
    .catch((error) => {
        console.log(error);
    })
    .finally(() => {
        console.log("Payment process completed.");
    });
Output
Payment successful!
Payment process completed.

7. Promise Chaining

Promise chaining allows us to perform multiple operations in sequence. Each then() can return a value or another Promise for the next step.

JavaScript
Promise.resolve(10)
    .then((marks) => {
        console.log("Original marks: " + marks);
        return marks + 5;
    })
    .then((total) => {
        console.log("Updated marks: " + total);
    })
    .catch((error) => {
        console.log("Error: " + error);
    });
Output
Original marks: 10
Updated marks: 15
Promise Chaining Diagram
Promise
↓
.then()
First operation returns a value
↓
.then()
Next operation receives that value
↓
.catch()
Handles errors in the chain

8. Important Promise Methods

Method Purpose
then() Handles fulfillment and can transform the result.
catch() Handles rejection or errors in the chain.
finally() Runs after settlement, regardless of outcome.
Promise.all() Fulfills when all input Promises fulfill; rejects if an input rejects.
Promise.allSettled() Waits until all input Promises settle.
Promise.race() Settles with the first input Promise to settle.
Promise.any() Fulfills with the first fulfilled input Promise, or rejects if all reject.

9. Important Points to Remember

  • A Promise represents the eventual result of an operation.
  • Its states are pending, fulfilled, and rejected.
  • resolve() fulfills a Promise; reject() rejects it.
  • then() handles fulfillment and supports chaining.
  • catch() handles rejection.
  • finally() runs after settlement.
  • Promises help structure asynchronous operations without deeply nested callbacks.

Summary

In this lesson, we learned how to create Promises, understand Promise states, handle fulfillment and rejection using then() and catch(), use finally(), and chain multiple operations. Examples involving Samadhan, Pradnya, and CIIT Training Institute demonstrate how Promises can represent real-world tasks.