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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

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

πŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay