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

Success Path: Using the Result

Accessing and working with the data parameter when no error occurred.

Success Path: Using the Result

You'll learn how to safely extract and use the data returned by an asynchronous operation when the error parameter is null or undefined.

What This Means

In the error-first callback pattern, when err is null or undefined, it signals success — the operation completed without problems. At that point, the second parameter (commonly named data or result) contains the value you actually wanted. Your job is to work with that data only after confirming no error occurred.

Think of it like checking your mailbox: if there's no "package damaged" notice (error), you can safely open and use what's inside (data).

The Success Branch

Once you've verified the error is absent, you access the result parameter:

function readUserProfile(userId, callback) {
  // Simulating async operation
  setTimeout(() => {
    callback(null, { id: userId, name: 'Alice' });
  }, 100);
}

readUserProfile(42, (err, user) => {
  if (err) {
    console.error('Failed to load user:', err.message);
    return;
  }

  // SUCCESS PATH: err is null, so user is safe to use
  console.log('Welcome, ' + user.name);
  console.log('User ID:', user.id);
});

Notice how the success code only runs after the error check. This prevents trying to access properties on undefined or null if an error occurred.

Multiple Success Operations

You can chain logic, transform data, or pass it to other functions:

fetchData('users/123', (err, data) => {
  if (err) {
    return handleError(err);
  }

  // Safe to destructure and use data
  const { name, email } = data;
  updateUI(name, email);
  logActivity('user_viewed', data.id);
});

Key Takeaway: The success path executes only when err is falsy; always access the data parameter after confirming no error exists, preventing runtime crashes from undefined values.