Understanding how JavaScript handles asynchronous code is key to writing smooth, non-blocking apps.
1️⃣ Callbacks
A function passed as an argument and called after an operation finishes.
function fetchData(callback) {
setTimeout(() => {
callback("Data loaded");
}, 1000);
}
fetchData(result => console.log(result)); // Data loaded❗ Problems: Callback hell, hard to debug
2️⃣ Promises
Promises are cleaner and solve callback hell.
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched"), 1000);
});
};
fetchData()
.then(res => console.log(res))
.catch(err => console.error(err));🔹
.then() handles success 🔹
.catch() handles error3️⃣ Async/Await
Simplifies Promises using synchronous-looking code.
const fetchData = () => {
return new Promise(resolve => {
setTimeout(() => resolve("Data received"), 1000);
});
};
async function getData() {
const result = await fetchData();
console.log(result);
}
getData(); // Data received🧠 Real Use Case: Fetching API data
async function loadUser() {
try {
const res = await fetch("https://api.example.com/user");
const data = await res.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}🎯 Practice Tasks:
• Convert a callback to a promise
• Write a function that uses async/await
• Handle errors with
.catch() and try-catch 💬 Tap ❤️ for more