A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/async-await-function-in-javascript/ below:

Async and Await in JavaScript

Async and Await in JavaScript

Last Updated : 10 Jun, 2025

Async and Await in JavaScript are used to simplify handling asynchronous operations using promises. By enabling asynchronous code to appear synchronous, they enhance code readability and make it easier to manage complex asynchronous flows.

JavaScript
async function fetchData() {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
  const data = await response.json();
  console.log(data);
}

fetchData();

Output:

{
userId: 1,
id: 1,
title: ....',
body: ....}
Syntax:
async function functionName() {
try {
const result = await someAsyncFunction();
console.log(result);
} catch (error) {
console.error("Error:", error.message);
}
}
Async Function

The async function allows us to write promise-based code as if it were synchronous. This ensures that the execution thread is not blocked. Async functions always return a promise. If a value is returned that is not a promise, JavaScript automatically wraps it in a resolved promise.

Syntax:

async function myFunction() {
  return "Hello";
}
javascript
const getData = async () => {
    let data = "Hello World";
    return data;
}

getData().then(data => console.log(data));
Await Keyword

The await keyword is used to wait for a promise to resolve. It can only be used within an async block. Await makes the code wait until the promise returns a result, allowing for cleaner and more manageable asynchronous code.

javascript
const getData = async () => {
    let y = await "Hello World";
    console.log(y);
}

console.log(1);
getData();
console.log(2);
Error Handling in Async/Await

JavaScript provides predefined arguments for handling promises: resolve and reject.

JavaScript
async function fetchData() {
  try {
    let response = await fetch('https://api.example.com/data');
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
Advantages of Async and Await
Async and Await in JavaScript

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4