Understanding Async/Await and Promises in JavaScript

Table of contents

No heading

No headings in the article.

Asynchronous programming is a key feature of modern web development. In JavaScript, asynchronous operations are commonly handled using Promises and more recently, the async/await syntax. In this blog post, we'll dive into what Promises and async/await are, how they work, and provide examples of how to use them in your code.

Promise :
A Promise represents a value that may not be available yet, but will be resolved in the future. Promises allow you to specify what should happen when an operation is complete, and what should happen if an error occurs.

Promises have three states:

  • pending: The initial state of a Promise. This means that the operation is still in progress.

  • fulfilled: The state of a Promise when the operation is successful. The Promise now has a resolved value.

  • rejected: The state of a Promise when the operation fails. The Promise now has a reason for rejection.

function fetchData() {
  return fetch('https://jsonplaceholder.typicode.com/posts')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));
}

fetchData();

In this example, the fetchData function returns a Promise that fetches data from an API. The .then method is used to convert the response to JSON and log the data to the console. The .catch method is used to log any errors that occur during the operation.

Async/Await :
Async/await allows you to write asynchronous code that looks and behaves like synchronous code. When a function is marked with the async keyword, it always returns a Promise. Inside the function, you can use the await keyword to wait for the result of an asynchronous operation.

async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

fetchData();

In this example, the fetchData function is marked with the async keyword, which means it returns a Promise. Inside the function, the await keyword is used to wait for the fetch operation to complete and for the response to be converted to JSON. The data is then logged to the console.

Async/await can also be used with error handling:

async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

fetchData();

In this example, the fetchData function checks if the response from the API was successful by checking the ok property of the Response object. If the response was not successful, an error is thrown. Otherwise, the data is logged to the console.

Conclusion :
Async/await and Promises are both powerful tools for handling asynchronous operations in JavaScript. Promises are a way to handle asynchronous operations using a chain of methods, while async/await is a more synchronous way of handling these operations.