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! π
Top comments (0)