DEV Community

Tomas Stveracek
Tomas Stveracek

Posted on

Understanding Callback Functions with a Practical Example

Imagine you are a chef and you have a helper. Your job is to cook dinner, but first, you need to get some special ingredients from the store. You ask your helper to go to the store, and when they come back, they tell you that they have the ingredients so you can continue cooking.

What We Need:

  • Node.js installed on your computer.
  • The node-fetch package, which helps us fetch data from the internet.

Installing Node.js and node-fetch

First, make sure you have Node.js installed. If not, you can download and install it from nodejs.org.

Then, open your terminal and install the node-fetch package by running this command: npm install node-fetch

Example: Fetching Real Data Using a Callback Function

The following example shows how to fetch real data from an API using a callback function.

// Function that fetches data from the API and then calls the helper (callback)
const fetchData = async (callback) => {
  console.log('Fetching ingredients from the store...');
  try {
    const fetch = (await import("node-fetch")).default;
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    const data = await response.json();
    console.log('Ingredients have been fetched.');
    callback(data); // Calling the helper (callback) with the fetched ingredients
  } catch (error) {
    console.error('Error fetching ingredients:', error);
  }
};

// Implementing and passing the helper (callback) to fetchData
fetchData((data) => {
  console.log('Processing the fetched ingredients:', data);
});
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

1/ Function fetchData:

  • Think of this function as your helper who goes to the store for ingredients.
  • This function is asynchronous (async), meaning it can wait for operations like fetching data.
  • It fetches data from the URL https://jsonplaceholder.typicode.com/posts/1, like going to the store to get special ingredients.
  • After successfully fetching the data, it converts it to JSON format, like coming back from the store with the ingredients.
  • Finally, it calls the helper (callback function) with the fetched data.

2/ Callback Function:

  • This function is like you, the chef, waiting for the ingredients.
  • Once the helper brings the ingredients, the chef (callback function) uses them to continue cooking.
  • In our case, this function logs the fetched data to the console.

Running the Code

Open the terminal in VS Code (or use the command line) and navigate to the directory where your fetchDataExample.js file is located. Then run this file using Node.js with the command: node fetchDataExample.js

What You Should See:

When you run this code, you should see something like this:

Fetching ingredients from the store...
Ingredients have been fetched.
Processing the fetched ingredients: { userId: 1, id: 1, title: '...', body: '...' }
Enter fullscreen mode Exit fullscreen mode

Summary:

  • You are the chef who needs ingredients to cook.
  • Your helper (callback function) goes to the store to fetch the ingredients (fetching data from the internet using node-fetch).
  • The helper brings the ingredients and tells you (calls the callback function with the fetched data).
  • You use these ingredients and continue cooking (processing the fetched data).

Top comments (0)