How to use callbacks in Node.js
· Category: Node.js
Short answer
A callback is a function passed as an argument to an asynchronous function that is executed once the operation completes. Node.js follows the error-first convention.
Steps
- Define a function that accepts a callback:
function readData(callback) { ... }. - Invoke the callback on success:
callback(null, result);. - Invoke the callback on error:
callback(new Error('Failed'));. - Call the function:
readData((err, result) => { if (err) { ... } else { ... } });. - Avoid deeply nested callbacks by extracting named functions or using promises.
Tips
- Always check for errors first in your callback implementation.
- The error-first pattern
(err, data)is a universal convention in the Node.js ecosystem.
Common issues
- Deeply nested callbacks lead to callback hell and make code hard to read.
- Forgetting to return after calling
callback(err)may cause double invocations.