JavaScript: Step 7- Promises and Async/Await

Promises and Async/Await are two features in JavaScript that are used for handling asynchronous operations. Asynchronous operations are tasks that take some time to complete, such as fetching data from a server or reading a file from disk. Promises and Async/Await provide a way to write code that can handle these tasks without blocking the main thread.

  1. Promises:

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. A Promise can be in one of three states: pending, fulfilled, or rejected. When a Promise is fulfilled, it means that the operation was successful and the Promise returns a value. When a Promise is rejected, it means that the operation failed and the Promise returns an error.

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 the above example, we create a Promise that returns a random number between 0 and 1 after a delay of 1 second. If the number is greater than 0.5, the Promise is resolved and the number is returned. If the number is less than or equal to 0.5, the Promise is rejected and an error message is returned. We then use .then() to handle the fulfilled Promise and .catch() to handle the rejected Promise.

  1. Async/Await:

Async/Await is a syntactic sugar for working with Promises. Async/Await allows us to write asynchronous code that looks like synchronous code. Async functions always return a Promise, and we can use the await keyword to wait for a Promise to resolve before continuing with the rest of the code.

Example program:

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

async function greet() {
  console.log("Hello");
  await delay(1000);
  console.log("World");
}

greet();

In the above example, we define an async function greet() that logs “Hello” to the console, waits for 1 second using the delay() function, and then logs “World” to the console. We call the greet() function, which returns a Promise that resolves after the delay.

By using Promises and Async/Await, we can write asynchronous code that is easy to read and understand. Promises allow us to handle the eventual completion (or failure) of an asynchronous operation, while Async/Await provides a way to write asynchronous code that looks like synchronous code.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.