JavaScript async & await


Async/Await is a modern and cleaner way to handle asynchronous code in JavaScript, especially when working with Promises. It makes asynchronous code look and behave like synchronous code, improving readability and maintainability.



What is async?

  • The async keyword is used to declare a function that always returns a Promise.
  • If the function returns a value, it's automatically wrapped in a Promise.resolve().

Example:

async function greet() {
return "Hello, world!";
}
greet().then(console.log); // Output: Hello, world!


What is await?

  • The await keyword is used inside async functions.
  • It pauses the execution of the function until the Promise is resolved or rejected.

Example:

function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function showSteps() {
console.log("Step 1");
await delay(1000);
console.log("Step 2");
await delay(1000);
console.log("Step 3");
}
showSteps();

Output

Step 1
(wait 1s)
Step 2
(wait 1s)
Step 3


Real-World Example: Fetching API Data

async function fetchPost() {
try {
const response = await
fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await response.json();
console.log("Post Title:", data.title);
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchPost();


Benefits of async/await Over .then()

Feature .then() /
.catch()
async/await
Readability Nested or chained Looks like synchronous code
Error handling .catch() Try...catch block
Ideal for Simple chains Complex async logic


Important Notes

  • await only works inside an async function
  • It pauses the async function, but doesn't block the rest of the program
  • Use try...catch for proper error handling