Beginner Fundamentals
Callbacks
A callback is a function passed to another function to be called later, usually when an asynchronous task finishes. Callbacks were the original way Node.js handled async work.
A simple callback
function greet(name, callback) {
console.log("Hi " + name);
callback();
}
greet("Fausto", () => {
console.log("Done");
});
Error-first callbacks
Node.js follows a convention: the first argument of a callback is the error (or null if all went well), and the result comes after.
const fs = require("fs");
fs.readFile("note.txt", "utf8", (err, data) => {
if (err) {
return console.error("Failed:", err.message);
}
console.log("Content:", data);
});
Always check the error first before using the data.
Callback hell
Nesting many callbacks gets hard to read:
doA((err) => {
doB((err) => {
doC((err) => {
// deeply nested
});
});
});
This problem is why Promises and async/await were introduced.
Summary
Callbacks run code after an async task. Follow the error-first convention, and switch to Promises when nesting gets deep.