DEV Community

PONVEL M
PONVEL M

Posted on

Async and Await in JavaScript (Easy Explanation for Freshers)

After understanding asynchronous JavaScript, the next important concept is async and await.
They help us write asynchronous code in a simple and readable way.

πŸ”Ή What is async?

*async is a keyword used before a function.
*

**It tells JavaScript:

This function will work with asynchronous code and always returns a Promise.**

Example
`async function greet() {
return "Hello World";
}

greet().then(result => console.log(result));`

πŸ”Ή What is await?

await is used inside an async function.

It tells JavaScript:

Wait here until the asynchronous task is completed, then continue.

πŸ”Ή Simple Example (Code)

`function getData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data received");
}, 2000);
});
}

async function showData() {
console.log("Fetching data...");
const result = await getData();
console.log(result);
}

showData();`

Output
Fetching data...
Data received

Even though it waits, the browser does not freeze.

🌍 Real-Life Example (Very Easy)
πŸ“¦ Online Shopping Example

Without await:

  • You order a product
  • You keep asking β€œIs it delivered?”
  • Code becomes confusing 😡

With async / await:

  • You place an order πŸ›’
  • You wait peacefully
  • When delivery arrives, you open it πŸ“¦ ➑️ Clean, readable, and easy to understand

**

πŸ”‘ Why Use Async & Await?

**

  • Makes asynchronous code look like synchronous
  • Easy for freshers
  • Avoids messy .then() chains
  • Better readability and debugging

**

πŸ“Œ Rules to Remember

**

  • await only works inside async functions
  • async functions return a Promise
  • await pauses the function, not the whole program

Top comments (0)