A callback function is a function passed as an argument to another function, which is then invoked inside the outer function to complete a specific routine or asynchronous operation.
flowchart TD
subgraph Sync ["Synchronous Callback"]
S1["[1, 2].map(fn)"] --> S2["Executes immediately in line"] --> S3["Returns array"]
end
subgraph Async ["Asynchronous Callback"]
A1["fetchData(url, callback)"] --> A2["Offloaded to Web API background"] --> A3["Callback triggered when I/O completes"]
end
| Callback Category | Execution Moment | Example APIs |
|---|---|---|
| Synchronous Callback | Executed immediately during parent call execution. | Array.prototype.map(), filter(), forEach() |
| Asynchronous Callback | Executed later after current call stack clears. | setTimeout(), addEventListener(), fs.readFile() |
// Demonstrating Asynchronous Callbacks and Callback Hell (Pyramid of Doom)
// 1. Asynchronous Callback Pattern with Error-First Convention
function fetchUserAsync(userId, callback) {
setTimeout(() => {
if (userId <= 0) {
callback(new Error("Invalid User ID"), null);
return;
}
const user = { id: userId, username: "maksudur_dev" };
callback(null, user); // Error-first callback convention (error, data)
}, 100);
}
// 2. Consuming Async Callback safely
fetchUserAsync(101, (err, user) => {
if (err) {
console.error(`Callback Error: ${err.message}`);
return;
}
console.log("Successfully fetched user:", user);
});
// 3. Callback Hell Demonstration (Nested Pyramid of Doom)
/*
fetchUserAsync(1, (err, user) => {
fetchOrders(user.id, (err, orders) => {
fetchOrderDetails(orders[0].id, (err, details) => {
// Hard to read, maintain, or handle errors properly!
});
});
});
*/
(err, result) where the first parameter is reserved for errors.async/await.Refactor a nested callback chain into flat modular helper functions.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.