DEV Community

Erasmus Kotoka
Erasmus Kotoka

Posted on

πŸŒ€ Understanding Asynchronous JavaScript: Callbacks, Promises, and Async/Await

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!"));



Enter fullscreen mode Exit fullscreen mode

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));

Enter fullscreen mode Exit fullscreen mode

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();

Enter fullscreen mode Exit fullscreen mode

✨ 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

Top comments (0)