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:
{Syntax:
userId: 1,
id: 1,
title: ....',
body: ....}
async function functionName() {Async Function
try {
const result = await someAsyncFunction();
console.log(result);
} catch (error) {
console.error("Error:", error.message);
}
}
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() {javascript
return "Hello";
}
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.
const getData = async () => {
let y = await "Hello World";
console.log(y);
}
console.log(1);
getData();
console.log(2);
JavaScript provides predefined arguments for handling promises: resolve and reject.
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
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