JavaScript: Step 7- Promises and Async/Await

image 2

Play Store Application link – Java to JavaScript in 13 Steps – App on Google Play

When dealing with tasks that take some time to complete, such as fetching data from a server or reading a file, JavaScript uses Promises and Async/Await to handle these asynchronous operations. These features allow you to write code that handles these tasks without freezing the main thread.

1. Promises

A Promise is an object that represents the eventual result of an asynchronous operation. It can be in one of three states:

  • Pending: The operation is still ongoing.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Example Program:

let promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    let num = Math.random();
    if (num > 0.5) {
      resolve(num);
    } else {
      reject("Error: Number is less than 0.5");
    }
  }, 1000);
});

promise
  .then((result) => {
    console.log(`Result: ${result}`);
  })
  .catch((error) => {
    console.error(error);
  });

In this example:

  • A Promise is created that generates a random number after 1 second.
  • If the number is greater than 0.5, the Promise is resolved with the number.
  • If the number is less than or equal to 0.5, the Promise is rejected with an error message.
  • .then() handles the resolved value, and .catch() handles any errors.

Comparison to Java:

In Java, handling asynchronous tasks often involves using Futures or CompletableFutures.

2. Async/Await

Async/Await provides a more readable way to work with Promises. It allows you to write asynchronous code that looks like synchronous code. An async function always returns a Promise, and await pauses the execution until the Promise is resolved.

Example Program:

function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function greet() {
  console.log("Hello");
  await delay(1000); // Waits for 1 second
  console.log("World");
}

greet();

In this example:

  • delay() is a function that returns a Promise that resolves after a specified number of milliseconds.
  • greet() is an async function that logs “Hello”, waits for 1 second using await, and then logs “World”.

Comparison to Java:

In Java, the equivalent to async and await would be using asynchronous constructs from libraries like CompletableFuture, but the syntax is more verbose.

Summary

  • Promises: Represent the eventual result of an asynchronous operation and can be handled using .then() and .catch().
  • Async/Await: Syntactic sugar over Promises that makes asynchronous code look and behave like synchronous code, improving readability and maintainability.

Using Promises and Async/Await makes it easier to handle asynchronous operations, leading to cleaner and more understandable code.


Leave a Reply

Your email address will not be published. Required fields are marked *