0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Async Await in JavaScript: Simple Guide

Use async before a function to make it return a promise, and use await inside that function to pause execution until a promise resolves. This lets you write asynchronous code that looks like normal synchronous code.
📐

Syntax

The async keyword is placed before a function declaration to mark it as asynchronous. Inside this function, you can use await before a promise to wait for its result without blocking the whole program.

  • async function: Declares an asynchronous function that returns a promise.
  • await expression: Pauses the function until the promise resolves and returns the resolved value.
javascript
async function fetchData() {
  const result = await fetch('https://api.example.com/data');
  const data = await result.json();
  return data;
}
💻

Example

This example shows how to use async and await to fetch data from a URL and log the result. It demonstrates how the code waits for the fetch to complete before continuing.

javascript
async function getUser() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
    const user = await response.json();
    console.log('User name:', user.name);
  } catch (error) {
    console.error('Error fetching user:', error);
  }
}

getUser();
Output
User name: Leanne Graham
⚠️

Common Pitfalls

Common mistakes include:

  • Using await outside an async function causes a syntax error.
  • Not handling errors with try/catch inside async functions can crash your program.
  • Forgetting that async functions always return a promise, so you need to handle them accordingly.
javascript
/* Wrong: await used outside async function */
// const data = await fetch('https://api.example.com'); // SyntaxError

/* Right: await inside async function with error handling */
async function loadData() {
  try {
    const response = await fetch('https://api.example.com');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Failed to load data:', error);
  }
}

loadData();
📊

Quick Reference

Remember these tips when using async and await:

  • Always mark functions with async if you want to use await inside.
  • Use try/catch to handle errors from awaited promises.
  • await pauses only the async function, not the whole program.
  • Async functions return promises, so use .then() or await when calling them.

Key Takeaways

Use async before a function to enable await inside it.
await pauses the async function until the promise resolves, making code easier to read.
Always handle errors in async functions with try/catch to avoid crashes.
Async functions return promises, so handle their results accordingly.
await cannot be used outside async functions.