Home >Web Front-end >JS Tutorial >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.
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
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); });
1/ Function fetchData:
2/ Callback Function:
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
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: '...' }
The above is the detailed content of Understanding Callback Functions with a Practical Example. For more information, please follow other related articles on the PHP Chinese website!