DEV Community

Erasmus Kotoka
Erasmus Kotoka

Posted on

1

πŸŒ€ 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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here β†’

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs