Now, we are going to look at a common real-life example: getting data from a server using an asynchronous callback in JavaScript. In this example, I'll use the XMLHttpRequest
object to make a simple HTTP request and a callback function to handle the response.
// Simulating an asynchronous HTTP request
function fetchDataFromServer(callback) {
// Creating a new XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configuring the request
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
// Setting up a callback function to handle the response
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
// Check if the request was successful (status code 200)
if (xhr.status === 200) {
// Parse the JSON response
var responseData = JSON.parse(xhr.responseText);
// Invoke the callback with the data
callback(null, responseData);
} else {
// If there was an error, invoke the callback with an error object
callback('Error fetching data from the server', null);
}
}
};
// Sending the request
xhr.send();
}
// Callback function to handle the fetched data
function handleData(error, data) {
if (error) {
console.error('Error:', error);
} else {
console.log('Fetched data:', data);
}
}
// Initiating the data fetching process
fetchDataFromServer(handleData);
In this example:
The
fetchDataFromServer
function initiates an asynchronous HTTP GET request to a JSONPlaceholder API endpoint.It accepts a callback function (
handleData
) as an argument.The
onreadystatechange
event is used to listen for changes in the state of the request. When the request is complete (readyState === 4
), the callback function is invoked with the fetched data or an error, depending on the success or failure of the request.The
handleData
callback function is defined separately and handles the fetched data or logs an error message.
In conclusion, the use of callback functions in JavaScript is an effective way to handle asynchronous operations such as fetching data from a server. This method allows your program to continue executing other tasks while waiting for the server response, thereby improving overall efficiency. By passing the callback function as an argument, you can control how the fetched data or possible errors are handled once the asynchronous operation is complete.