Callbacks

Callbacks


The Messenger Bird

Imagine you're a general in ancient Japan, planning a strategic move that requires information from a distant scout. You send a messenger bird with a note asking for the latest reports. The callback function is like this messenger bird: you don't just wait idly for its return; instead, you continue with your duties. When the bird returns (the asynchronous task completes), it delivers the message (the callback function is called), and you can make informed decisions based on the new information.

Flight of the Callback

Wings cut through the sky,
Callback with the awaited news,
Silence breaks, code flies.

The Tea Ceremony Promise

function sendMessage(request, callback) {
  console.log("Messenger bird sent with request: " + request);
  // Simulating the time taken for the bird to return
  setTimeout(() => {
    const response = "Scout reports enemy movements";
    callback(response);
  }, 2000);
}

function processMessage(response) {
  console.log("Received from scout: " + response);
}

// Send the message and define what to do once the response arrives
sendMessage("Need latest enemy positions", processMessage);

Callback

Bird Arrives, Code Kicks: BACK

Just like waiting for a bird to deliver a message before acting, a callback waits for an asynchronous event to complete before kicking in with its action.

Concept Checking Questions

  1. What is a callback function in JavaScript?

    • A callback function is a function passed into another function as an argument, which is then executed inside the outer function to complete some kind of routine or action.
  2. Why are callbacks important in JavaScript?

    • Callbacks are essential for asynchronous operations, allowing the program to continue running while waiting for an operation to finish, thus not blocking the main thread.
  3. Can you give an example of a common use case for callbacks?

    • A common use case for callbacks is in web development, for instance, fetching data from a server where the callback function is executed once the data has been received.