async function?
An asynchronous function is a special type of function in JavaScript defined using the async keyword. It allows you to write non-blocking code in a more readable and cleaner way using await.
It always returns a Promise.
Promise-based code easier to read and maintain.
async function functionName() {
// You can use await inside here
}
async – Declares that a function is asynchronous and returns a Promise.await – Pauses the execution inside async until the promise settles.Promise – An object representing the result of an async operation.
async function greet() {
return "Hello!";
}
greet().then(msg => console.log(msg)); // Output: Hello!
await
function fetchData() {
return new Promise(resolve => {
setTimeout(() => resolve("Data loaded"), 2000);
});
}
async function loadData() {
console.log("⏳ Loading...");
const data = await fetchData(); // Waits for 2 seconds
console.log("✅", data);
}
loadData();
Imagine ordering a pizza 🍕. You place the order (fetchData()), then go do other stuff while you wait. When it arrives, you eat it (await). Async functions let your program do something else while waiting, instead of sitting idle.
try...catch inside async to handle errors.await outside async functions (unless top-level await is supported).async and await are just syntax sugar for using Promises.
async function getUser() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
const user = await response.json();
console.log(user);
} catch (err) {
console.error("Fetch error:", err);
}
}
getUser();
async functions return promises.await pauses code until the promise resolves.