DEV Community

Arhan Khan
Arhan Khan

Posted on

Promises and Async/Await in JavaScript: Stop the Callback Mess

A promise is JavaScript's answer to "this will take a while". Instead of nesting callbacks inside callbacks, you get an object that represents a future value — and async/await lets you write asynchronous code that reads like synchronous code.

A promise has three states: pending, fulfilled, or rejected. fetch returns one, and .then() runs when it fulfils:

fetch("https://api.example.com/users")
  .then((response) => response.json())
  .then((users) => console.log(users))
  .catch((error) => console.error("Failed:", error));
Enter fullscreen mode Exit fullscreen mode

Every .then() returns a new promise, so the chain stays flat. The .catch() at the end handles a failure anywhere in the chain — one error handler instead of one per step.

async/await is the same machinery with cleaner syntax. Mark a function async and it returns a promise; await pauses the function until the promise settles:

async function loadUsers() {
  try {
    const response = await fetch("https://api.example.com/users");
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const users = await response.json();
    console.log(users);
  } catch (error) {
    console.error("Failed:", error);
  }
}
Enter fullscreen mode Exit fullscreen mode

The try/catch is the part beginners skip — an await that rejects without a catch becomes an unhandled rejection, which is a silent bug in production.

Independent requests should run in parallel, not one after another. Promise.all waits for all of them:

async function loadDashboard() {
  const [users, posts, comments] = await Promise.all([
    fetch("/api/users").then((r) => r.json()),
    fetch("/api/posts").then((r) => r.json()),
    fetch("/api/comments").then((r) => r.json()),
  ]);
  return { users, posts, comments };
}
Enter fullscreen mode Exit fullscreen mode

Three requests in sequence take the sum of their times; in parallel they take the longest one. But Promise.all rejects if any request fails — use Promise.allSettled when you want the results that succeeded even if one failed.

You can also create a promise yourself, which is how you wrap older callback APIs:

function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function demo() {
  console.log("Start");
  await wait(1000);
  console.log("One second later");
}
Enter fullscreen mode Exit fullscreen mode

Two mistakes beginners make: first, forgetting await — the function returns a pending promise and the next line runs with undefined data. Second, await inside a loop for independent items, which turns parallel work into a slow queue — map to promises first, then await Promise.all.

Ways to extend it: add a timeout with Promise.race so a slow API cannot hang your page, retry a failed request with a small loop and exponential backoff, or convert a callback-based library to promises with a wrapper like the wait example above. Async code is where junior developers struggle most — and where this pattern pays off fastest.

Top comments (0)