What is async/await in JavaScript

6/28/2025

JavaScript example using await to resolve a promise

Go Back

What is async/await in JavaScript?

async and await are syntactic sugar introduced in ES2017 (ES8) that make working with Promises easier and more readable. They allow you to write asynchronous code that looks and behaves like synchronous code, making it simpler to understand and maintain.


  JavaScript example using await to resolve a promise

What is an async Function?

An async function always returns a Promise. You can use await inside it to pause the execution of the function until a Promise resolves or rejects.

Syntax:

async function fetchData() {
  // Your asynchronous code here
}

What is the await Keyword?

The await keyword pauses the function execution until the Promise resolves. It only works inside an async function. If the Promise is rejected, an error is thrown and can be caught using try...catch.

Example:

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

async function showData() {
  const result = await getData();
  console.log(result); // Output: "Data received"
}

showData();

 Handling Errors with try...catch

async/await works seamlessly with try...catch blocks, allowing developers to handle errors in a straightforward and readable way.

Example:

async function fetchWithError() {
  try {
    let result = await fetch('invalid-url');
    let data = await result.json();
    console.log(data);
  } catch (error) {
    console.error("Error occurred:", error.message);
  }
}

 

Benefits of Using async/await

  • Cleaner and more readable than chaining .then()/.catch()

  • Easier debugging and error handling using try...catch

  • Mimics synchronous code structure, improving comprehension

Table of content