Nearby lessons
17 of 21🔄 Node.js – Callback Pattern & Callback Functions
📌 What is Callback?
What is a Callback?
A callback is a function passed as an argument to another function. It allows a function to call another function and can run after another function has finished. Callback functions can also be returned as values from other functions.
This is a fundamental pattern in Node.js to handle asynchronous operations.
📌 Example: Simple Callback
Compare easy understanding of callback and higher-order function:
Node.js Environment
function show1(name) { console.log(`Hello ${name}`); } function show2(showName) { const name = "Coding Point"; showName(name); } show2(show1);
⚡ Types of Callbacks
- Synchronous Callbacks
- Asynchronous Callbacks
✅ Synchronous Callbacks
A callback function which is executed immediately is called a synchronous callback.
Example: see the previous 'Simple Callback' example.
⏳ Asynchronous Callbacks
An asynchronous callback is used to continue or resume code execution after an asynchronous operation has completed.
Example use cases: fetching 50,000 rows from a database or reading a file with 50,000 lines. The callback function executes after the operation completes.
🌐 Asynchronous Callbacks – Browser Example
Node.js Environment
function callback() { document.getElementById("demo").innerHTML = "Hello World"; } document.getElementById("btn").addEventListener("click", callback);
🌐 Asynchronous Callbacks – jQuery Example
Node.js Environment
$.get("url", function(data) { $(".result").html(data); alert("Load was performed."); });
📂 Asynchronous Callbacks in Node.js
Node.js uses asynchronous callbacks to prevent blocking of execution.
Node.js Environment
const fs = require("fs"); fs.readFile("demo.txt", (err, data) => { if (err) throw err; console.log(data.toString()); });