DEV Community

ENG-CJ
ENG-CJ

Posted on

Mastering Callbacks in JavaScript πŸ’»πŸ”₯

Image description

Basics of Callbacks 😊

Callbacks are functions passed as arguments to other functions, enabling the invocation of code at a specific point during or after an asynchronous operation. They serve as a mechanism for handling the results or errors of these operations.

Let's explore a simple example to understand how callbacks work in practice

function fetchData(callback) {
  setTimeout(() => {
    const data = 'Hello, World!';
    callback(data);
  }, 2000);
}

function processData(data) {
  console.log(`Received data: ${data}`);
}
fetchData(processData);

Enter fullscreen mode Exit fullscreen mode

In this example, the fetchData function simulates an asynchronous operation by using setTimeout. It accepts a callback function and invokes it with the retrieved data. The processData function serves as the callback, receiving and processing the data once it's available.

Advanced Callback Patterns

function fetchData(callback, errorCallback) {
  setTimeout(() => {
    const error = false;
    if (error) {
      errorCallback(new Error('Data retrieval failed!'));
    } else {
      const data = 'Hello, World!';
      callback(data);
    }
  }, 2000);
}

function processData(data) {
  console.log(`Received data: ${data}`);
}

function handleFetchError(error) {
  console.error(`Error: ${error.message}`);
}

fetchData(processData, handleFetchError);

Enter fullscreen mode Exit fullscreen mode

In this revised example, the fetchData function introduces an errorCallback parameter. If an error occurs during the asynchronous operation, the errorCallback is invoked with an Error object. The handleFetchError function acts as the error callback, providing a standardized approach to handle errors.

In Conclusion, Callbacks are the backbone of JavaScript's asynchronous programming paradigm. By mastering callbacks, you empower yourself to handle complex asynchronous scenarios efficiently. In this post, we covered the basics of callbacks, advanced patterns like error handling, and techniques to avoid callback hell. Armed with this knowledge, you'll be well-equipped to write robust and scalable JavaScript code. Embrace the power of callbacks and unlock the true potential of JavaScript!

Top comments (0)