How can code be structured to handle events or asynchronous operations?
Here are common approaches to structuring code for events and asynchronous operations:
1. Callback Functions:
Concept: A function is passed as an argument to another function, with the understanding that it will be invoked later when an event occurs or an asynchronous operation completes.
Example:
function fetchData(url, callback) {
// Simulate a network request (asynchronous)
setTimeout(() => {
const data = { message: "Data fetched!" };
callback(data); // Call the callback function when data is ready
}, 1000);
}
fetchData("https://example.com/data", (fetchedData) => {
console.log(fetchedData); // Output: { message: "Data fetched!" } after 1 second
});
2. Promises:
Concept: Objects that represent the eventual result of an asynchronous operation, with methods to handle success (.then()) and failure (.catch()) outcomes.
Example:
function fetchDataPromise(url) {
return new Promise((resolve, reject) => {
// Simulate a network request
setTimeout(() => {
const data = { message: "Data fetched!" };
resolve(data); // Resolve the promise with data on success
}, 1000);
});
}
fetchDataPromise("https://example.com/data")
.then((fetchedData) => {
console.log(fetchedData); // Output: { message: "Data fetched!" } after 1 second
})
.catch((error) => {
console.error("Error fetching data:", error);
});
3. Async/Await (JavaScript):
Concept: Syntactic sugar built on top of promises, making asynchronous code appear more like synchronous code.
Example:
async function fetchDataAsync(url) {
try {
const response = await fetch(url); // Using the built-in fetch API
const data = await response.json();
return data;
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchDataAsync("https://example.com/data")
.then((fetchedData) => {
console.log(fetchedData); // Output: fetched data
});
4. Event Listeners:
Concept: Functions registered to respond to specific events triggered by the system or user interactions.
Example:
button.addEventListener("click", () => {
console.log("Button clicked!");
});
Follow us on LinkedIn : https://www.linkedin.com/in/raj-kamal-302bb4200/