🌀 Understanding Asynchronous JavaScript: Callbacks, Promises, and Async/Await
Erasmus Kotoka
Posted on September 19, 2024
Asynchronous JavaScript allows code to run without freezing the whole page, making it essential for smooth user experiences.
Here’s a quick breakdown of the key tools for handling asynchronous tasks in
JavaScript:
1️⃣ Callbacks
Callbacks are functions passed into other functions as arguments, executed after the main function completes.
🚦 Example:
function fetchData(callback) {
setTimeout(() => {
console.log("Data fetched!");
callback();
}, 2000);
}
fetchData(() => console.log("Processing complete!"));
2️⃣ Promises
Promises are a cleaner way to handle asynchronous operations.
They either resolve (success) or reject (failure), which helps you manage responses effectively.
✨ Example:
let dataPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data received!"), 2000);
});
dataPromise.then(result => console.log(result)).catch(error => console.log(error));
3️⃣ Async/Await
Async/Await is the modern way of handling asynchronous code, making it easier to read and write.
It's built on Promises but looks more like synchronous code.
🚀 Example:
async function getData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
getData();
✨ In Summary:
Callbacks: Basic but can lead to "callback hell."
Promises: Cleaner and more structured.
Async/Await: Makes async code feel synchronous and easier to understand.
Mastering these will make you a pro at handling real-time data, fetching APIs, and more! 😎
CODEWith #KOToka
Posted on September 19, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024