JavaScript Async/Await

In JavaScript, async/await is a modern approach for handling asynchronous operations in a clear and readable manner. It is built on top of Promises, it allows developers to write code that looks synchronous while still being non-blocking. 

The ‘async’ keyword is used to define a function that returns a promise, while the ‘await’ keyword pauses execution until the promise resolves or rejects. This eliminates the need for chaining ‘.then()’ and ‘.catch()’ methods, making code easier to understand and maintain. 

Overall, async/await improves code structure, simplifies error handling, and enhances the developer experience when working with asynchronous tasks.

 

Understanding ‘async’

The ‘async’ keyword is used to declare a function as asynchronous. An async function always returns a Promise, even if you return a simple value.

 

async function greet() {

  return “Hello World”;

}

 

greet().then(console.log); // Hello World

 

 

Understanding ‘await’

The ‘await’ keyword is used inside an async function to pause execution until a Promise is resolved or rejected.

 

async function getData() {

  let promise = new Promise((resolve) => {

    setTimeout(() => resolve(“Data received”), 2000);

  });

 

  let result = await promise;

  console.log(result);

}

getData();

 

Here, ‘await’ waits for the promise to resolve before moving to the next line.

 

 

Why Use Async/Await?

Before async/await, developers used:

  •  Callbacks – Callbacks in JavaScript often lead to callback hell, making code deeply nested and hard to read. Error handling becomes inconsistent, and debugging is difficult. As applications grow, managing multiple callbacks becomes confusing and unscalable, which is why modern approaches like Promises and async/await are preferred for cleaner, more maintainable code.
  •  Promises (‘.then()’) – Promises improve asynchronous handling but have some limitations. Chaining multiple `.then()` calls can still make code harder to read, especially in complex workflows. Error handling, while better than callbacks, can become tricky if not properly managed. Promises also lack built-in cancellation, making it difficult to stop ongoing operations. Additionally, overusing promises without proper structure can lead to less readable code.

 

These approaches often made code harder to read. Async/await simplifies this by making code look linear and easier to understand.

 

Example: Without Async/Await (Using Promises)

 

fetch(“https://jsonplaceholder.typicode.com/users”)

  .then(response => response.json())

  .then(data => console.log(data))

  .catch(error => console.log(error));

 

 

 
Example: With Async/Await

 

async function fetchUsers() {

  try {

    const response = await fetch(“https://jsonplaceholder.typicode.com/users”);

    const data = await response.json();

    console.log(data);

  } catch (error) {

    console.log(error);

  }

}

fetchUsers();

 

 

 This version is cleaner and easier to read.

 

 

Error Handling with Async/Await

You can use ‘try…catch’ to handle errors:

 

async function loadData() {

  try {

    const res = await fetch(“https://api.example.com/data”);

    const data = await res.json();

    console.log(data);

  } catch (error) {

    console.log(“Error:”, error);

  }

}

 

Important Points to Remember
  •  ‘async’ makes a function return a Promise
  •  ‘await’ pauses execution until the Promise resolves
  •  ‘await’ can only be used inside async functions

 

Real-World Example

 

Async/await is widely used in:

  •  API calls
  •  Data fetching
  •  File handling
  •  Frameworks like React

 

Advantages of Async/Await

  •  Cleaner and more readable code: Async/await makes code look simple and structured, similar to synchronous code.
  •  Easier debugging: It allows step-by-step debugging without dealing with nested callbacks.
  •  Better error handling: Errors can be handled easily using `try…catch` blocks.
  •  Eliminates complex `.then()` chains: Avoids long promise chains, making code easier to understand and maintain.

 

 

Async/await is a powerful feature that simplifies working with asynchronous JavaScript. It allows developers to write code that is easier to understand while still handling complex asynchronous operations efficiently.Async/await lets you write asynchronous code in a synchronous style, making your JavaScript cleaner, more readable, and easier to maintain.

 

Scroll to Top