DEV Community

Cover image for Then vs Await in JavaScript: When and How to Use
TenE
TenE

Posted on

1

Then vs Await in JavaScript: When and How to Use

Introduction

JavaScript is asynchronous, meaning some operations (like API calls) take time to complete. Instead of blocking execution, JavaScript uses Promises to handle async tasks efficiently. To manage these Promises, we use then() and await to ensure smooth and structured execution of asynchronous operations.

1. Understanding then() (Promise Chaining)

The .then() method is used to handle the result of a Promise after it resolves. It allows method chaining, enabling multiple asynchronous operations to be executed in sequence.

Syntax:

promise.then(successCallback).catch(errorCallback);
Enter fullscreen mode Exit fullscreen mode

Example:

fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then((response) => response.json()) // Convert response to JSON
  .then((data) => console.log(data)) // Handle retrieved data
  .catch((error) => console.error("Error:", error)); // Handle errors
Enter fullscreen mode Exit fullscreen mode

When to Use then() ?

  • When you prefer method chaining for handling Promises.
  • When working with callback-based libraries like fetch().
  • When not using async/await.

2. Understanding await (Inside Async Functions)

The await keyword pauses execution until a Promise resolves. It must be used inside an async function to ensure synchronous-looking code.

Syntax:

async function myFunction() {
  let result = await somePromise;
}
Enter fullscreen mode Exit fullscreen mode

Example:

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

fetchData();
Enter fullscreen mode Exit fullscreen mode

When to Use await?

  • When you need cleaner, synchronous-looking async code.
  • When handling multiple async calls in sequence.
  • When inside an async function.

3. then() vs await: A Side-by-Side Comparison

Feature then() await
Syntax Style Callback-based Synchronous-looking
Error Handling .catch() try...catch
Readability Can become hard to manage with deep .then() chains Cleaner and easier to follow
Usage Scope Works anywhere Only inside async functions

4. Why Should You Use then() or await?

Using then() or await helps us:

  • Handle async operations efficiently (e.g., API calls, database queries).
  • Avoid callback hell (deeply nested callbacks that reduce readability).
  • Write cleaner, structured, and more readable code.
  • Ensure sequential execution when needed.

5. When to Choose then() or await?

Use then() when chaining simple Promises.

fetch("https://api.example.com/user")
  .then((res) => res.json())
  .then((user) => fetch(`https://api.example.com/posts/${user.id}`))
  .then((res) => res.json())
  .then((posts) => console.log(posts))
  .catch((err) => console.error("Error:", err));
Enter fullscreen mode Exit fullscreen mode

Use await when handling multiple async calls sequentially.

async function getUserPosts() {
  try {
    let resUser = await fetch("https://api.example.com/user");
    let user = await resUser.json();

    let resPosts = await fetch(`https://api.example.com/posts/${user.id}`);
    let posts = await resPosts.json();

    console.log(posts);
  } catch (error) {
    console.error("Error:", error);
  }
}

getUserPosts();
Enter fullscreen mode Exit fullscreen mode

6. Recommended Approach

For most cases, await is recommended due to its improved readability and ease of debugging. However, in scenarios where multiple independent Promises need to be resolved simultaneously, consider using Promise.all() with await:

async function fetchMultipleData() {
  try {
    let [user, posts] = await Promise.all([
      fetch("https://api.example.com/user").then((res) => res.json()),
      fetch("https://api.example.com/posts").then((res) => res.json()),
    ]);

    console.log(user, posts);
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

fetchMultipleData();
Enter fullscreen mode Exit fullscreen mode

Best Practices:

  • Use await for sequential async tasks inside async functions.
  • Use then() for method chaining or handling Promises outside async functions.

Summary:

  • Use await for most async operations due to better readability.
  • Use then() when method chaining is preferable.
  • Use Promise.all() with await for parallel async tasks to improve performance.

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Tutorial image

Next.js Tutorial 2025 - Build a Full Stack Social App

In this 4-hour hands-on tutorial, Codesistency walks you through the process of building a social platform from scratch with Next.js (App Router), React, Prisma ORM, Clerk for authentication, Neon for PostgreSQL hosting, Tailwind CSS, Shadcn UI, and UploadThing for image uploads.

Watch the full video ➡