JavaScript
Error-first callbacks
Learn the Node.js error-first callback convention.
The error-first callback convention
Node.js has a common convention for error handling in asynchronous operations: the callback takes the error as the first parameter. If there is no error, this parameter is null; if there is, it is an Error object. The other parameters carry the result.
function readUser(id, callback) {
setTimeout(() => {
callback(null, { id: id });
}, 100);
}
This convention is known as the error-first callback. When invoking the callback, you check the error first; this reduces the risk of forgetting to handle errors.
Check the error first
When using an error-first callback, you check the first parameter first. If there is an error, you do not use the result; if there is none, err is null and you can safely use the result.
readUser(1, (err, user) => {
if (err) {
console.log('Error:', err.message);
return;
}
console.log('User:', user.id);
});
Returning early with return prevents accidentally reaching the result after handling an error. This pattern is very common in Node.js.
Exercise Write the readConfig function
Define a function named readConfig. It should take a single parameter: callback. Inside the function, use setTimeout to call callback after 100 ms with null and a config object. Since there is no error, the first argument must be null.
Show example solution
function readConfig(callback) {
setTimeout(() => {
callback(null, { theme: 'dark' });
}, 100);
}
Test yourself
-
Which is an error-first callback signature?
- callback(err, data)
- callback(result)
- callback(error)
- callback(data, err)
Show answer
callback(err, data) — Correct! The first parameter is the error (err), the second is the result (data).
-
Complete the error check
readUser(1, (err, user) => {
if (____) {
console.log('Error:', err.message);
return;
}
});
Show answer
readUser(1, (err, user) => {
if (err) {
console.log('Error:', err.message);
return;
}
});
-
Match the concepts
- err parameter
- First argument
- null err
- No error
- new Error()
- Error object
- callback(err, data)
- Error first
-
What does err === null mean in an error-first callback?
- An error occurred
- The callback was not called yet
- The operation succeeded, no error
- There is no result
Show answer
The operation succeeded, no error — Correct! A null err means there is no error and the result can be used.
Next lesson: Callback hell