Callbacks in Node
A callback in Node often takes the error first. The first input is the error, and the next inputs carry the result.
A timer callback
This callback runs after three seconds. It takes no inputs.
setTimeout(() => {
console.log("Three seconds passed");
}, 3000);An error-first callback
This callback gets an error message. It prints the message and stops.
function fail(callback) {
callback("No file found");
}
fail((error) => {
if (error) console.log(error);
});Example
function greet(name, callback) {
callback(null, "Hello, " + name);
}
greet("Node", (error, message) => {
if (error) {
console.log("Something went wrong");
return;
}
console.log(message);
});Key points
- An error-first callback takes the error as its first input.
- The error is null when the work went well.
- Null means no value, so null error means no error.
- The result follows the error as the next input.
- Check the error first, and stop when an error is present.
- A callback runs after its work finishes, not before.
In this example, greet takes a name and a callback. It calls the callback with null for the error and a greeting as the result. The callback checks the error first, and the error is null. The callback then prints the greeting, Hello, Node.
Note
Always pass null for the error when the work succeeds.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is the first input of an error-first callback?