How Async / Await work in JavaScript?

How Async / Await work in JavaScript - by SR Programist


When i start learning JavaScript so in this i felt handle asynchronous task using Promises is hard because my code looked messy and also use long .then() chains that make code hard to read. but when I learned async and await. It made asynchronous code look clean, readable, and almost synchronous.

In this guide, I’ll explain async/await in a simple, practical way that actually helps you write better JavaScript.



What Is Async / Await in JavaScript?

Async and await are JavaScript keywords that help you write asynchronous code in a cleaner and more readable way.

  • async defines an asynchronous function
  • await pauses execution until a Promise resolves

Async/await is built on top of Promises.



Why Async / Await Exists

Before async/await, developers used callbacks and Promise chains, which often resulted in unreadable and hard-to-maintain code.

Async/await solves this by:

  • Improving code readability
  • Reducing nested logic
  • Making error handling easier


Basic Async Function Example


async function greetUser() {
  return "Hello, welcome!";
}
    

An important thing to remember is that an async function always returns a Promise.



greetUser().then(message => {
  console.log(message);
});
    


What Does await Do?

The await keyword pauses execution inside the async function until the Promise is resolved.



async function fetchData() {
  const response = await fetch("/api/data");
  const data = await response.json();
  console.log(data);
}
    

JavaScript waits for the response, but the rest of the application continues running smoothly.



Async / Await vs Promise .then()

Promise-Based Code


fetch("/api/user")
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });
    


Same Code Using Async / Await


async function getUser() {
  try {
    const response = await fetch("/api/user");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
    

Async/await is easier to read, debug, and maintain.



Real-World Example

In real web applications, async/await is used for:

  • API calls
  • Authentication
  • Database requests
  • Payment processing

async function loginUser(credentials) {
  const response = await fetch("/api/login", {
    method: "POST",
    body: JSON.stringify(credentials)
  });

  return await response.json();
}
    


🎥 Async / Await Video Tutorial





Common Beginner Mistake


const data = await fetch("/api/data"); // ❌ Error
    

await can only be used inside an async function.



async function loadData() {
  const data = await fetch("/api/data");
}
    


Error Handling With Async / Await

Async/await allows clean error handling using try...catch.



async function fetchUsers() {
  try {
    const response = await fetch("/api/users");
    const users = await response.json();
    console.log(users);
  } catch (error) {
    console.error("Something went wrong:", error);
  }
}
 


Is Async / Await Blocking?

No. Async/await is non-blocking. It pauses execution only inside the function, while the rest of the JavaScript continues running.



When Should You Use Async / Await?

  • Fetching data from APIs
  • Handling background tasks
  • Working with Promises
  • Writing clean asynchronous code


Best Practices

  • Use try...catch for error handling
  • Avoid unnecessary await
  • Keep async functions small
  • Do not mix .then() with async/await


Summary

  • Async/await simplifies asynchronous JavaScript
  • async functions return Promises
  • await pauses execution until resolved
  • Cleaner code and better error handling


Conclution

Once you start using async/await, writing asynchronous JavaScript becomes easier, cleaner, and more professional.

👉 Don’t forget to like, share, and subscribe to our channel  SR Programist and also Follow us on other Social media platforms for more web development tutorials! 

Post a Comment

Post a Comment (0)

Previous Post Next Post