Understanding Callback Functions in TypeScript: A Beginner’s Guide
Suresh Krishnan Nair
Posted on March 30, 2024
What are Callback Functions?
Callback functions are functions passed as arguments to other functions and executed at a later time or after a specific event. They allow us to define behavior that should occur once a certain task is completed. Imagine them as “callbacks” to let you know when something has finished.
Exploring the Structure of a Callback Function:
Higher-Order Function: The function that takes a callback function as an argument.
Callback Function: The function passed as an argument to the higher-order function.
Asynchronous Task: The task that takes time to complete (e.g., fetching data from a server).
Completion Event: Triggered when the asynchronous task is finished.
Illustrating with a Diagram:
+-----------------------------+
| Higher-Order Function |
+-----------------------------+
| |
| +----------------------+ |
| | Callback Function | |
| +----------------------+ |
| | | |
| | (Task Completed) | |
| | | |
| +----------------------+ |
| |
+-----------------------------+
|
|
+-----------------------------+
| Asynchronous Task |
+-----------------------------+
|
|
+-----------------------------+
| Completion Event |
+-----------------------------+
Example in TypeScript:
function fetchData(callback: (data: any) => void) {
// Simulate fetching data asynchronously
setTimeout(() => {
const data = 'Sample data 1';
callback(data);
}, 5000);
console.log("Initiated "); // Added log message to see when fetchData is initiated
// Simulate fetching more data asynchronously after a delay
setTimeout(() => {
const data = 'Sample data 2';
callback(data);
}, 6000);
}
// Usage of the callback function
fetchData((data) => {
console.log('Data received:', data);
});
Output:
Initiated
Data received: Sample data 1
Data received: Sample data 2
Explanation:
Let’s break down the provided TypeScript example into its components:
Higher-Order Function: fetchData
- fetchData is the higher-order function in this example.
- It takes a callback function as a parameter.
- The callback function represents the behavior that should occur once the data is fetched.
Callback Function Parameter: (callback: (data: any) => void)
- The callback function parameter is defined in the fetchData function signature.
- It accepts a function as an argument, which takes one parameter data of type any and returns void.
- This parameter is a function reference that will be invoked when the data fetching operation completes.
Asynchronous Task: setTimeout
- Inside the fetchData function, there are two setTimeout calls, which simulate asynchronous tasks.
- These asynchronous tasks represent the fetching of data from an external source.
- Each setTimeout call has a delay before executing its callback function, mimicking the time taken to fetch the data.
Completion Event: Callback Invocation
- The completion event occurs when the setTimeout functions execute their callback functions.
- Inside each setTimeout callback function, the callback parameter (the provided callback function) is invoked with the fetched data as an argument.
Usage of the Callback Function:
- The fetchData function is called with a callback function as an argument.
- This callback function defines what should be done with the fetched data.
- In this example, the callback function logs the received data to the console.
Execution Flow:
- The fetchData function is called with a callback function as an argument.
- Inside fetchData, the asynchronous tasks (data fetching) are initiated using setTimeout.
- After the specified delay, each setTimeout executes its callback function.
- Inside each callback function, the provided callback function (callback) is invoked with the fetched data.
- The provided callback function handles the received data as specified in its definition.
Overall, this example illustrates how callback functions can be used to handle asynchronous operations, allowing us to define behavior that occurs once the asynchronous tasks are completed.
Disclaimer: “This article was created with the help of AI”
Posted on March 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.