Home JavaScript Tutorial Async and Await in javascript

Async and Await in javascript

by Anup Maurya
23 minutes read

In this article, you’ll learn about Async and Await in javascript along with error handling.

In JavaScript, the async and await keywords provide a simpler way to work with asynchronous code based on promises. Here’s a brief overview:

  1. async Function: When you declare a function with the async keyword, it automatically returns a promise. This allows you to use the await keyword inside the function to wait for promises to resolve. For example:
async function fetchData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}
  1. await Operator: The await keyword can only be used inside an async function. It pauses the execution of the function until the promise is settled (fulfilled or rejected). It then returns the result of the promise. For example:
async function fetchData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}
  1. Error Handling: You can use try...catch blocks to handle errors when using async and await. If a promise rejects, the catch block will handle the error. For example:
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
  1. Usage: You can call async functions and use await to wait for their results. Remember that await can only be used inside an async function or in a JavaScript module. For example:
async function displayData() {
  const data = await fetchData();
  console.log(data);
}

displayData();

Using async and await can make your asynchronous code more readable and easier to manage compared to using nested callbacks or promise chains.

related posts

Leave a Comment

Enable Notifications OK No thanks