Welcome, JavaScript adventurers! In this chapter, we delve into the world of callback functions, a fundamental concept in asynchronous programming. Callback functions allow you to define code that gets executed after a long-running operation finishes. Buckle up as we explore the fundamentals, practical applications, and advanced considerations of callback functions in JavaScript.
function buyCoffee(size, callback) {
const time = Math.random() * 2000; // Simulate brewing time (random delay)
setTimeout(() => {
const coffee = `Here's your ${size} coffee!`;
callback(coffee); // Call the callback function with the result (coffee)
}, time);
}
buyCoffee("large", function(coffee) {
console.log(coffee); // Output: Here's your large coffee! (after random delay)
});
console.log("This line executes immediately (before coffee is ready)");
buyCoffee
function takes two arguments: size
and a callback
function.setTimeout
and a random delay.callback
function with the prepared coffee.console.log
statement outside the callback function executes immediately, demonstrating non-blocking behavior.
function getUserData(userId, callback) {
// Simulate fetching data from a server (replace with actual fetch API call)
const userData = { name: "Alice", age: 30 };
setTimeout(() => {
callback(userData);
}, 1000);
}
getUserData(123, function(data) {
console.log(data); // Output: { name: "Alice", age: 30 } (after 1 second)
});
console.log("This line executes before user data is retrieved");
getUserData
simulates fetching user data (here, a dummy object).callback
).getUserData
with a user ID and our callback function to handle the data.
function fetchDataFromServer(url, callback) {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function() {
if (xhr.status === 200) {
callback(null, JSON.parse(xhr.responseText)); // Pass null for no error, data as argument
} else {
callback(new Error("Failed to fetch data"), null); // Pass error and null for data
}
};
xhr.onerror = function() {
callback(new Error("Network error"), null);
};
xhr.send();
}
fetchDataFromServer("https://api.example.com/data", function(error, data) {
if (error) {
console.error(error);
} else {
console.log(data);
}
});
XMLHttpRequest
(older approach) to simulate fetching data from a server.callback
function now receives two arguments: error
(if any) and data
(if successful).Error
object as the first argument to the callback function.Callback Chaining: While not ideal due to potential complexity, callback chaining allows you to perform multiple asynchronous operations one after another, passing data between them. However, promises (covered later) offer a cleaner solution.
Callback functions are a foundational concept in asynchronous programming. They provide a way to handle long-running operations without blocking the main thread. However, they have limitations, especially regarding code readability and error handling. Happy coding !❤️