Course contentsShow
← JavaScript
Lesson 1232 of 2,72328. CallbacksFree lesson

What Are Error-First Callbacks?

Understanding the Node.js convention where callbacks receive an error as the first argument.

What Are Error-First Callbacks?

You'll learn the standard Node.js convention for handling errors in callback functions.

The Convention

Error-first callbacks (also called "Node-style callbacks") are a pattern where callback functions always receive an error object as their first argument, followed by any result data. If no error occurred, the first argument is null or undefined.

This convention provides a consistent, predictable way to handle both success and failure cases when working with asynchronous operations.

The Pattern Structure

function doAsyncTask(callback) {
  // If something goes wrong:
  callback(new Error('Something went wrong'), null);
  
  // If everything succeeds:
  callback(null, 'success result');
}

The callback always checks the error first:

doAsyncTask(function(err, result) {
  if (err) {
    console.error('Error occurred:', err.message);
    return; // Stop execution on error
  }
  
  console.log('Success:', result);
});

Why This Matters

Before this convention became standard, different libraries handled errors differently—some threw exceptions, others passed errors in different argument positions. Error-first callbacks created a universal contract: always check the first parameter for errors.

Think of it like a quality inspector at a factory who always checks the reject bin first before handling good products. You establish a consistent routine: check for problems, then proceed only if safe.

Real-World Example

function readUserData(userId, callback) {
  if (!userId) {
    callback(new Error('User ID required'), null);
    return;
  }
  
  // Simulate successful data retrieval
  setTimeout(function() {
    callback(null, { id: userId, name: 'Alice' });
  }, 100);
}

readUserData(42, function(err, userData) {
  if (err) {
    console.error('Failed:', err.message);
    return;
  }
  console.log('User loaded:', userData.name);
});

Key Takeaway: Error-first callbacks always pass errors as the first argument and results as subsequent arguments, establishing a consistent pattern for handling both failure and success cases in asynchronous code.