Have you heard about Hack Frontend Community?Join us on Telegram!
Practice JS Problems

async/await in JavaScript: How It Works Under the Hood

async and await are syntactic sugar over promises, introduced in ES2017, which allows writing asynchronous code as if it were synchronous.

  • async — makes function asynchronous, automatically returning Promise.
  • awaitpauses execution inside async function until promise completes (successfully or with error).

Simple Example

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

async function greet() {
  console.log("Waiting...");
  await delay(1000); // Wait 1 second
  console.log("Hello after 1 second!");
}

greet();

async: How Does it Work?

async function foo() {
  return 42;
}

foo().then(result => console.log(result)); // 42

Even if function returns simple value, async wraps it in Promise.

await: How Does it Work?

async function fetchUser() {
  const res = await fetch("/user.json");
  const data = await res.json();
  return data;
}
  • await pauses execution until fetch returns result.
  • After completion, result is passed to variable and execution continues.

Error Handling

With async/await it's convenient to use try/catch:

async function getData() {
  try {
    const response = await fetch("/api");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("An error occurred:", error);
  }
}

Features

  • await can only be used inside async function.
  • await only works with promises (or any thenable objects).
  • If await returns error, it's thrown and caught in catch.

Summary

  • async/await makes asynchronous code understandable, linear and clean.
  • It doesn't replace promises, but simplifies their use.
  • Always handle errors with try/catch or .catch().

Good to Know:

await doesn't block main thread! It only pauses current async function execution, freeing thread for other tasks.

Practice JS Problems

By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.