JavaScript Tutorial ✦
Error-First Callback Pattern
Error-first callback can be used in JavaScript, especially in the Node.js environment. When we pass callbacks in a function, in error-first callbacks, the first argument is always the error, followed by other things like data, variables, etc.
In that specific function, we first check if there is an error. If there’s no error, then only the main code block will run.
For example, if we are accessing a file from the local machine using the fs
module, the first argument will be the error. Then we will show the main data that we accessed only if there’s no error.
Here’s a code example:
function accessData(error, data) {
if (error) {
console.log(error); // If there is an error, data access will not work
} else {
console.log(data, "data is accessed"); // If no error is found, then this code block will run
}
}
Error-first callback is the safest and standard way to help with smooth execution of the code and to prevent it from crashing.
function readFile(path, callback) {
fs.readFile(path, (err, data) => {
if (err) return callback(err);
callback(null, data);
});
}