DEV Community

Cover image for Asynchronous Programming and Promises in JavaScript
Abhishek Raina
Abhishek Raina

Posted on

Asynchronous Programming and Promises in JavaScript

Asynchronous Programming and Promises in JavaScript:

Let’s break down these concepts in a fun and easy-to-understand way!

  • What is Asynchronous Programming?

Asynchronous programming is like having a superpower that allows your code to do multiple things at once without getting stuck. In traditional synchronous programming, tasks are executed one after the other, like a single-threaded chef who can only cook one dish at a time. This can lead to long wait times, especially when tasks take a while, like fetching data from a server.

Example of Synchronous vs. Asynchronous:

1. Synchronous:

console.log("Start cooking");
// Waits for the dish to finish
console.log("Dish is ready!");
Enter fullscreen mode Exit fullscreen mode

2. Asynchronous:

console.log("Start cooking");
setTimeout(() => console.log("Dish is ready!"), 3000); // Cook for 3 seconds
console.log("I can do other things while waiting!");
Enter fullscreen mode Exit fullscreen mode

In the asynchronous example, the chef starts cooking and immediately moves on to other tasks while the dish is cooking in the background. This is the magic of asynchronous programming!

  • Enter the Promises

Image description

Now, let’s meet Promises—the trusty sidekick of asynchronous programming. A Promise is like a waiter who promises to bring you your order. You place your order (make a request), and the waiter assures you that they will deliver it later, even if you have to wait a bit.

  • Promise States:
  1. Pending: The initial state; the promise is still waiting for the operation to complete.
  2. Fulfilled: The operation was completed successfully, and the promise has a value.
  3. Rejected: The operation failed, and the promise has a reason for the failure.
  • Creating a Promise:
let orderDish = new Promise((resolve, reject) => {
  let cookingTime = 3000; // 3 seconds
  setTimeout(() => {
    resolve("Dish is ready!"); // Fulfilled
  }, cookingTime);
});

Enter fullscreen mode Exit fullscreen mode
  • Using Promises: .then() and .catch()

Once you have your Promise, you can use .then() to handle the successful completion of the task and .catch() to handle any errors.

orderDish
  .then((message) => console.log(message)) // If fulfilled
  .catch((error) => console.log(error));   // If rejected
Enter fullscreen mode Exit fullscreen mode

Async/Await: The Cool Sibling of Promises

Image description

Now, let’s introduce the async/await syntax. It allows you to write asynchronous code that looks synchronous, making it easier to read and maintain.

  1. Async: This keyword is used to declare a function as asynchronous.
  2. Await: This keyword is used to pause the execution of the async function until the Promise is resolved.

Example:

async function serveDish() {
  try {
    const message = await orderDish; // Wait for the promise to resolve
    console.log(message);
  } catch (error) {
    console.log(error);
  }
}

serveDish();
Enter fullscreen mode Exit fullscreen mode

Comparing .then() vs. await

1. .then():

  • Good for chaining multiple asynchronous operations.
  • Can lead to "callback hell" if not managed properly.

2. await:

  • Makes your code look cleaner and more readable.
  • Easier to handle errors with try/catch.

Learning Resources

To dive deeper into asynchronous programming and Promises, here are some resources that can help:

  • MDN Web Docs: A comprehensive guide to Asynchronous JavaScript.
  • Eloquent JavaScript: Chapter 11 covers asynchronous programming in detail.
  • FreeCodeCamp: Offers a Beginner's Guide to Asynchronous JavaScript.
  • JavaScript.info: A great resource for understanding Promises.

Top comments (0)