Open In App

What is the use of the async function in JavaScript?

The use of async functions in JavaScript is to simplify writing asynchronous code by using the async keyword. Async functions allow you to write asynchronous code in a synchronous-like manner, making it easier to manage and understand asynchronous operations.

Example: Here, fetchData() is an async function that fetches data from an API asynchronously using the fetch() function. The await keyword is used to wait for the asynchronous operation to complete, making the code appear synchronous. Async functions simplify working with Promises and improve the readability of asynchronous code.



async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}



Article Tags :