How can code be structured to handle events or asynchronous operations?

TechLoons
2 min readJan 9, 2024

Photo by Gabriel Heinzer on Unsplash

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/

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

TechLoons
TechLoons

Written by TechLoons

Welcome to TechLoons, your go-to source for the latest tips and information on a wide range of topics.

No responses yet

Write a response