0
0
JavascriptConceptBeginner · 3 min read

What is Async Await in JavaScript: Simple Explanation and Example

In JavaScript, async and await are keywords that help write asynchronous code in a way that looks and behaves like synchronous code. async marks a function to return a promise, and await pauses the function execution until the promise resolves, making code easier to read and manage.
⚙️

How It Works

Imagine you are cooking dinner and waiting for water to boil. Instead of standing and watching the pot, you do other tasks and come back when the water is ready. This is similar to how async and await work in JavaScript.

An async function always returns a promise. Inside this function, you can use await to pause the code until a promise finishes, like waiting for the water to boil. This pause only affects the async function, not the whole program, so other code can keep running.

This makes asynchronous code easier to write and understand because it looks like normal step-by-step code, but it still handles tasks that take time, like fetching data from the internet.

💻

Example

This example shows an async function that waits for a promise to resolve using await. It simulates a delay and then prints a message.

javascript
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function greet() {
  console.log('Waiting...');
  await delay(1000); // wait for 1 second
  console.log('Hello after 1 second!');
}

greet();
Output
Waiting... Hello after 1 second!
🎯

When to Use

Use async and await when you need to handle tasks that take time, like fetching data from a server, reading files, or waiting for timers. They help you write code that waits for these tasks to finish without blocking the whole program.

For example, when building a website that loads user information from the internet, async and await let you write clear code that waits for the data before showing it, improving user experience and code readability.

Key Points

  • async marks a function to return a promise.
  • await pauses the function until the promise resolves.
  • They make asynchronous code easier to read and write.
  • Only use await inside async functions.
  • They help avoid complex promise chains and callbacks.

Key Takeaways

Use async to declare functions that return promises.
Use await inside async functions to wait for promises to resolve.
Async/await makes asynchronous code look like simple, step-by-step code.
They improve code readability and help manage tasks like data fetching or timers.
Remember await only works inside async functions.