← Back to Chapters

JavaScript Async / Await

⚡ JavaScript Async / Await

? Quick Overview

async and await are modern JavaScript features that simplify working with Promises, making asynchronous code look and behave more like synchronous code. They help you write cleaner, more readable logic for tasks like fetching data from APIs, waiting for timers, or handling long-running operations.

? Key Concepts

  • async function always returns a Promise, even if you explicitly return a normal value.
  • await pauses the execution of an async function until a Promise settles (resolves or rejects).
  • You can handle success with normal code after await and handle errors using try...catch.
  • async/await is built on top of Promises – it’s just a nicer syntax, not a separate feature.

? Syntax & Theory

To declare an asynchronous function, use the async keyword before the function definition. Inside that function, you can use await in front of any expression that returns a Promise.

Key rules:

  • await can only be used inside an async function (in normal JavaScript files).
  • When the awaited Promise resolves, execution continues with the resolved value.
  • If the Promise rejects, an error is thrown at the await line and can be caught in a try...catch block.

? Code Examples

? async function returning a Promise

A simple async function that returns a value. JavaScript wraps this value in a Promise.

? View Code Example
async function myFunction() {
  return "Hello!";
}

myFunction().then(alert); // Alerts "Hello!"

⏳ Using await with fetch()

Here, await pauses the function until fetch() and then response.json() are completed.

? View Code Example
async function fetchData() {
  let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
  let data = await response.json();
  console.log(data);
}

⏱️ Waiting for a custom Promise

This example uses a Promise that resolves after 2 seconds using setTimeout(), then awaits it.

? View Code Example
function delay() {
  return new Promise(resolve => {
    setTimeout(() => resolve("Done!"), 2000);
  });
}

async function run() {
  console.log("Waiting...");
  let result = await delay();
  console.log(result); // "Done!"
}

run();

⚖️ Handling errors with try...catch

Use try...catch inside an async function to handle rejected Promises.

? View Code Example
async function loadData() {
  try {
    let response = await fetch("https://invalid-url.com");
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error:", error.message);
  }
}

? Async function still works with then()

An async function returns a Promise, so you can still use .then() on it if you want.

? View Code Example
async function getUser() {
  return "John";
}

getUser().then(alert); // Alerts "John"

? Interactive Example

Click the button to run an async function that simulates loading data with a delay.

? Demo Output

Click the button to see the async/await flow.

? Live Output / Explanation

? What the delay example does

  • Logs "Waiting..." immediately.
  • Calls delay(), which returns a Promise that resolves after 2 seconds.
  • await delay() pauses the run() function until the Promise resolves.
  • After 2 seconds, the Promise resolves with "Done!" and that value is logged.

This pattern is common when:

  • Waiting for data from a server (API calls).
  • Waiting for user actions or animations.
  • Simulating slow operations in demos or tests.

? When to Use Async / Await

  • Whenever you have multiple Promise-based operations that should happen in sequence.
  • When you want to avoid deeply nested .then() chains (“Promise hell”).
  • When you need clear error handling around several async steps in a row.

? Tips & Best Practices

  • Use async/await to make complex asynchronous flows easier to read and debug.
  • Always wrap critical await calls in try...catch to handle errors gracefully.
  • Remember: await can be used with any function that returns a Promise.
  • Don’t use await outside an async function in normal scripts – it will cause a syntax error.
  • Don’t forget to actually write await in front of a Promise-based call if you need to pause for its result.

? Try It Yourself

  • Create an async function that fetches a post from an API (for example, https://jsonplaceholder.typicode.com/posts/1) and logs only the title.
  • Wrap setTimeout() inside a Promise and use await to delay execution by a few seconds.
  • Intentionally use an invalid URL in fetch(), then catch and log the error using try...catch inside an async function.