JavaScript: Async Functions (In-Depth)

Async functions make it easier to write code that works with Promises. By writing async function, you can use await inside for a more readable, synchronous-looking style.

Declaring an Async Function

async function getData() {
  // code
}
    

Example: Fetching Data

async function fetchUser() {
  let res = await fetch("https://jsonplaceholder.typicode.com/users/1");
  let user = await res.json();
  console.log(user.name); // "Leanne Graham"
}
fetchUser();
    

Error Handling

async function demo() {
  try {
    let value = await Promise.reject("Oops!");
  } catch (e) {
    console.log("Caught:", e);
  }
}
demo();
    
// Output:
Caught: Oops!

Returning Values

async function add(a, b) {
  return a + b;
}
add(2, 3).then(result => console.log(result)); // 5
    

When to Use Async Functions

Practice: Convert then chains to async/await in your own code. Try error handling with try/catch!