🌶️The callback pattern

The callback pattern is a way of performing an action after a function has completed. A callback function is a function that is passed as an argument to another function, and is executed after the first function has completed.

Here is an example of the callback pattern:

function doSomething(callback) {
  // Perform some action
  console.log('Doing something...');

  // Call the callback function
  callback();
}

// This function will be passed as a callback
function doSomethingElse() {
  console.log('Doing something else');
}

doSomething(doSomethingElse);

In this example, the doSomething function takes a callback function as an argument. When the doSomething function is called, it performs some action and then calls the callback function.

The callback function, doSomethingElse, is defined separately and is passed as an argument to the doSomething function when it is called.

The output to the console will be:

Doing something...
Doing something else

The callback pattern is often used to perform an action after an asynchronous operation has completed. For example:

function getData(callback) {
  // This is an asynchronous operation
  fetch('https://example.com/data').then(response => {
    const data = response.json();

    // Call the callback function with the data
    callback(data);
  });
}

// This function will be passed as a callback
function displayData(data) {
  console.log(data);
}

getData(displayData);

In this example, the getData function performs an asynchronous operation to retrieve data from a server, and calls the callback function (displayData) with the data when it has been retrieved.

The callback pattern is a way of organizing code and performing actions after a function has completed. It allows you to write flexible and reusable code, and is a common pattern.

Last updated