DEV Community

Raisha Sultana
Raisha Sultana

Posted on

Async and Await Explained Clearly A Complete Guide for JavaScript Developers

JavaScript is a single-threaded language, but it can handle asynchronous operations efficiently. Tasks like fetching data from an API, reading files, or waiting for a timer do not block the main thread. To manage these operations, JavaScript uses asynchronous programming.

Two of the most important tools for handling asynchronous code are async and await. These keywords make asynchronous code easier to read, write, and maintain.

In this article, you will learn what async and await are, how they work, why they are important, and how to use them with real examples.

What is Asynchronous Programming in JavaScript

Before understanding async and await, you need to understand asynchronous programming.

Asynchronous programming allows JavaScript to run long-running tasks without blocking the rest of the code.

Example of synchronous code:

console.log("Start");

console.log("Task complete");

console.log("End");
Enter fullscreen mode Exit fullscreen mode

Output:

Start
Task complete
End
Enter fullscreen mode Exit fullscreen mode

Example of asynchronous code:

console.log("Start");

setTimeout(() => {
  console.log("Task complete");
}, 2000);

console.log("End");

Enter fullscreen mode Exit fullscreen mode

Output:

Start
End
Task complete

Enter fullscreen mode Exit fullscreen mode

The setTimeout function runs asynchronously. JavaScript does not wait for it to finish.

What is a Promise

Async and await are built on top of Promises. A Promise represents a future value that may be resolved or rejected.

Example:

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Data received");
  }, 2000);
});

promise.then((result) => {
  console.log(result);
});

Enter fullscreen mode Exit fullscreen mode

Output after 2 seconds:

Data received

Enter fullscreen mode Exit fullscreen mode

Promises solve callback problems but can still become hard to read when chained.

What is Async in JavaScript

The async keyword is used to define an asynchronous function. An async function always returns a Promise.

Example:

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

greet().then(console.log);

Enter fullscreen mode Exit fullscreen mode

Output:

Hello World

Enter fullscreen mode Exit fullscreen mode

Even though the function returns a string, JavaScript automatically wraps it in a Promise.

Equivalent code:

function greet() {
  return Promise.resolve("Hello World");
}

Enter fullscreen mode Exit fullscreen mode

What is Await in JavaScript

The await keyword is used inside async functions. It pauses the execution of the function until the Promise is resolved.

Example:

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

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

getData();

Enter fullscreen mode Exit fullscreen mode

Output after 2 seconds:

Data loaded

Enter fullscreen mode Exit fullscreen mode

The await keyword makes asynchronous code look like synchronous code.

Async and Await Example with API

This is a real-world example using fetch API.

Without async and await:

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

Enter fullscreen mode Exit fullscreen mode

With async and 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();

Enter fullscreen mode Exit fullscreen mode

This version is cleaner and easier to understand.

Why Use Async and Await

Async and await provide several benefits.

  1. Cleaner code

Async and await remove complex promise chains.

  1. Easier to read

The code looks like normal synchronous code.

  1. Better error handling

You can use try and catch blocks.

Common Mistakes to Avoid
Mistake 1: Forgetting async keyword

Wrong:

function test() {
  await fetchData();
}

Enter fullscreen mode Exit fullscreen mode

Correct

async function test() {
  await fetchData();
}

Enter fullscreen mode Exit fullscreen mode

Mistake 2: Not using try catch

Always handle errors.

Mistake 3: Using await unnecessarily

Use Promise.all for parallel operations.

When Should You Use Async and Await

Use async and await when:

Fetching data from APIs

Reading files

Database operations

Waiting for timers

Handling network requests

Avoid using it for simple synchronous tasks.

Async Await vs Promise: Comparison
Feature Promise Async Await
Readability Medium High
Error handling .catch() try catch
Syntax Complex Simple
Beginner friendly No Yes

Async and await are built on Promises but easier to use.

Conclusion

Async and await are essential tools in modern JavaScript. They simplify asynchronous programming and make code easier to read and maintain.

Key points to remember:

Async functions return Promises

Await pauses execution until Promise resolves

Use try catch for error handling

Async and await improve readability

Use Promise.all for parallel operations

If you are working with APIs, databases, or asynchronous tasks, mastering async and await is necessary.

Understanding async and await will help you write cleaner, more professional JavaScript code and prepare you for real-world development.

Top comments (0)