0
0
NodejsHow-ToBeginner · 3 min read

How to Use Callback in Node.js: Simple Guide with Examples

In Node.js, a 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.

javascript
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.

javascript
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);
  }
});
Output
Success: Processed: Hello
⚠️

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.

javascript
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}`);
}
Output
Result: First call
📊

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.

Key Takeaways

Callbacks in Node.js handle asynchronous results by passing a function as an argument.
The callback function usually receives an error as the first argument and the result as the second.
Always check for errors in the callback before processing results.
Never call the callback function more than once to avoid unexpected behavior.
Use callbacks to keep your code responsive and non-blocking.