JavaScript  

Async and Await in JavaScript with Example?

๐ŸŒ Introduction

In JavaScript, some tasks take time to complete, like fetching data from a server, reading files, or waiting for user input. These tasks should not block the whole program. If the program waits for one slow task, everything else would stop working. To solve this, JavaScript uses asynchronous programming.

The keywords async and await help us handle asynchronous code in a simple and readable way. They are built on top of Promises but allow us to write code that looks more like normal step-by-step code.

โšก What is async?

The async keyword is placed before a function to make it always return a Promise. Even if the function returns a simple value, JavaScript automatically wraps it inside a Promise.

This means whenever we call an async function, we get a Promise that we can use with .then() or await.

Example:

async function sayHello() {
  return "Hello C# Corner";
}

sayHello().then(message => console.log(message));
// Output: Hello C# Corner!

Here, sayHello() returns a string, but since itโ€™s marked as async, JavaScript turns it into a Promise.

โณ What is await?

The await keyword can only be used inside an async function. It makes JavaScript wait until a Promise is finished (resolved or rejected). After that, it continues to the next line of code.

This makes asynchronous code look like normal synchronous code.

Example:

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

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

getData();

// Output:
// Fetching data...
// (after 2 seconds)
// Data received!

Here, await fetchData() makes the program wait until the Promise finishes. Only then it prints the result.

๐Ÿ“Š Benefits of Using Async and Await

1. Readable Code

Without async/await, we use .then() many times which can look confusing. With async/await, the code looks like normal step-by-step instructions.

2. Easier Error Handling

We can use try...catch with async/await to handle errors in a cleaner way, instead of chaining .catch() with Promises.

3. Better Flow Control

Async/await lets us write code in a natural order without nesting too many callbacks or promise chains.

Example with Error Handling:

async function fetchUserData() {
  try {
    let response = await fetch("https://jsonplaceholder.typicode.com/users/1");
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

fetchUserData();

Here, if the server is down or the fetch fails, the error is caught in catch.

๐Ÿ”„ Async/Await vs Promises

Using Only Promises:

fetch("https://jsonplaceholder.typicode.com/users/1")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Using Async/Await:

async function getUser() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

getUser();

Both do the same thing, but the async/await version is much easier to read and understand.

๐Ÿ“ Summary

In JavaScript, async and await make it easier to work with asynchronous code. An async function always returns a Promise, and await makes the program wait until the Promise finishes. This makes code easier to read, write, and debug compared to using only Promises or callbacks. Async/await is very useful when working with API calls, file reading, or any task that takes time to complete.