Callbacks
A callback is a function you hand to another function to be called later when the work is done.
In this page:
Syntax
function functionName(args, callback) {
// do work
callback(err, result);
}
functionName(args, (err, result) => {
if (err) return handleError(err);
// use result
});
Callbacks
Node's classic style is error-first callbacks: the first argument is an error or null, followed by results. Deep nesting of callbacks leads to hard-to-read callback hell, which promises and async/await solve.
Note:
Always check the err argument first.
Example: Callbacks
function getUser(id, cb) {
setTimeout(() => {
if (id <= 0) return cb(new Error("bad id"));
cb(null, { id, name: "Ada" });
}, 5);
}
getUser(1, (err, user) => console.log(err ? err.message : user));
getUser(0, (err, user) => console.log(err ? err.message : user));
// Output:
// { id: 1, name: 'Ada' }
// bad id
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Ignoring the error argument
- Calling a callback twice
- Throwing inside async callbacks and crashing the process
Chapter Summary
- Callbacks run when work completes
- Error-first convention
- Nesting causes callback hell
- Always handle err
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: