Lesson 21 of 50 – Callbacks
42% Completed
42%

Node.js Callbacks

A callback is a function passed as an argument to another function. The receiving function can call the callback when a particular task is completed or when an event occurs.

In simple words: A callback is a function that we give to another function so it can be called later or at a specific point in the program.

1. What Is a Callback Function?

JavaScript allows us to pass functions as arguments. This makes callbacks useful for calculations, event handling, and asynchronous tasks such as reading files.

Example: Simple Callback
function greet(name, callback) {
    console.log('Hello ' + name);
    callback();
}

function message() {
    console.log('Welcome to Node.js!');
}

greet('Rahul', message);
Output:
Hello Rahul
Welcome to Node.js!

Here, message is passed as a callback. The greet() function calls it using callback().

2. Passing an Anonymous Function as a Callback

We can pass a function directly without giving it a separate name. Such a function is commonly called an anonymous function.

Example: Anonymous Callback
function calculate(a, b, callback) {
    callback(a + b);
}

calculate(10, 20, function (result) {
    console.log('Sum:', result);
});
Output:
Sum: 30

The callback receives the sum and displays it.

3. Using an Arrow Function as a Callback

Arrow functions can also be used as callbacks. They often make callback code shorter and easier to read.

Example: Arrow Callback
function calculate(a, b, callback) {
    callback(a * b);
}

calculate(5, 4, (result) => {
    console.log('Multiplication:', result);
});
Output:
Multiplication: 20

The arrow function receives the multiplication result and prints it.

4. Synchronous Callbacks

A synchronous callback is called during the execution of the function that receives it.

Example: Synchronous Execution
function processData(callback) {
    console.log('Processing data...');
    callback();
}

processData(function () {
    console.log('Data processed.');
});

console.log('Program finished.');
Output:
Processing data...
Data processed.
Program finished.

The callback executes before processData() returns.

5. Asynchronous Callbacks

An asynchronous callback can run later, after an operation or delay. Node.js uses callbacks for many asynchronous operations.

Example: Callback with setTimeout()
console.log('Start');

setTimeout(function () {
    console.log('Callback executed.');
}, 2000);

console.log('End');
Output:
Start
End
Callback executed.

The callback is scheduled to run after approximately two seconds. The synchronous statements run first.

6. Callback with Parameters

We can pass values to a callback so it can use the result of another operation.

Example: Calculate a Square
function calculateSquare(number, callback) {
    const result = number * number;
    callback(result);
}

calculateSquare(6, function (answer) {
    console.log('Square:', answer);
});
Output:
Square: 36

The calculated result is passed to the callback as an argument.

7. Error-First Callbacks in Node.js

Many Node.js APIs use the error-first callback pattern. The first argument represents an error, and the next argument or arguments contain the result.

If the operation succeeds, the error argument is usually null. If it fails, the callback receives an error.

Example: Error-First Callback
function divide(a, b, callback) {
    if (b === 0) {
        callback(new Error('Cannot divide by zero'));
        return;
    }

    callback(null, a / b);
}

divide(10, 2, function (err, result) {
    if (err) {
        console.log('Error:', err.message);
        return;
    }

    console.log('Result:', result);
});
Output:
Result: 5

The callback checks the error first. If an error exists, it handles the error and returns before using the result.

8. Callback with the File System Module

The Node.js File System module supports callback-based operations. For example, fs.readFile() can read a file asynchronously and pass its result to a callback.

Example: Read a File

First, create a file named message.txt:

Hello from a Node.js file!

Now create read.js:

const fs = require('fs');

fs.readFile('message.txt', 'utf8', function (err, data) {
    if (err) {
        console.log('Error:', err.message);
        return;
    }

    console.log(data);
});
Output:
Hello from a Node.js file!

The callback receives an error and the file contents. If the file cannot be read, the error is handled first.

9. Callback Hell

Callback hell occurs when several asynchronous operations are nested inside one another. Deep nesting can make code harder to read and maintain.

Example: Nested Callbacks
setTimeout(() => {
    console.log('Step 1');

    setTimeout(() => {
        console.log('Step 2');

        setTimeout(() => {
            console.log('Step 3');
        }, 1000);

    }, 1000);

}, 1000);
Output:
Step 1
Step 2
Step 3

For complex asynchronous workflows, Promises and async/await can make code easier to organize. We will study these in upcoming lessons.

10. Advantages of Callbacks

Why Use Callbacks?
  • They allow functions to be passed as arguments.
  • They are useful for asynchronous operations.
  • They help handle the results of file operations.
  • They allow code to run when an event or task completes.
  • They are used by many Node.js APIs.

11. Important Callback Concepts

Concept Meaning
Callback A function passed to another function.
Synchronous callback Runs during the current function call.
Asynchronous callback Runs later when the scheduled operation is ready.
Error-first callback Receives an error as its first argument.
Callback hell Deeply nested callbacks that are difficult to manage.
callback() Calls the function stored in the callback parameter.

📝 Practical Assignment

Practice Tasks
Write programs to complete these tasks:
  1. Create a function that accepts a name and a callback.
  2. Calculate the sum of two numbers using a callback.
  3. Calculate the square of a number and pass the result to a callback.
  4. Use setTimeout() to call a function after three seconds.
  5. Create a divide function that reports an error if the divisor is zero.
  6. Read a text file using fs.readFile() and handle possible errors.

Challenge: Create three asynchronous steps using callbacks and display their results in order.


🧠 Quiz – Node.js Callbacks

Select the correct answer for each question.

1. What is a callback function?

2. In a common Node.js error-first callback, what is the first argument?

3. Which function is commonly used to read a file asynchronously with a callback?