How to Use Callback in Node.js: Simple Guide with Examples
callback is a function passed as an argument to another function to run after an operation finishes. You use callbacks to handle asynchronous tasks by calling the callback with results or errors once the task completes.Syntax
A callback in Node.js is a function passed as the last argument to another function. The typical pattern is functionName(args, callback), where callback is called inside functionName after completing its task.
The callback usually has two parameters: error and result. If an error occurs, error is set; otherwise, result holds the successful output.
function doSomething(data, callback) { // simulate async task setTimeout(() => { if (!data) { callback(new Error('No data provided')); } else { callback(null, `Processed: ${data}`); } }, 1000); }
Example
This example shows a function doSomething that takes data and a callback. It simulates an asynchronous task with setTimeout. The callback receives an error or the processed result.
function doSomething(data, callback) { setTimeout(() => { if (!data) { callback(new Error('No data provided')); } else { callback(null, `Processed: ${data}`); } }, 1000); } doSomething('Hello', (error, result) => { if (error) { console.error('Error:', error.message); } else { console.log('Success:', result); } });
Common Pitfalls
Common mistakes include not handling errors in the callback, calling the callback multiple times, or forgetting to pass a callback function.
Always check for errors first in the callback and avoid calling the callback more than once.
function doSomethingWrong(data, callback) { // Calls callback twice - wrong callback(null, 'First call'); callback(null, 'Second call'); } doSomethingWrong('test', (error, result) => { if (error) { console.error('Error:', error.message); } else { console.log('Result:', result); } }); // Correct way: function doSomethingRight(data, callback) { if (!data) { callback(new Error('No data')); return; } callback(null, `Processed: ${data}`); }
Quick Reference
Remember these tips when using callbacks in Node.js:
- Callbacks are functions passed to handle results after async tasks.
- First callback argument is usually an error or
null. - Always check for errors before using results.
- Call the callback only once.
- Use arrow functions for concise callback syntax.