JavaScript: await (In-Depth)

The await keyword is used inside async functions to pause execution until a Promise is resolved. It gives asynchronous code a synchronous look.

Basic Usage

async function example() {
  let result = await Promise.resolve(123);
  console.log(result); // 123
}
example();
    

How await Works

Awaiting fetch()

async function fetchPost() {
  let res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
  let post = await res.json();
  console.log(post.title);
}
fetchPost();
    

Chaining Awaits

async function chain() {
  let a = await Promise.resolve(1);
  let b = await Promise.resolve(a + 1);
  return b;
}
chain().then(console.log); // 2
    

Error Handling with await

async function errorDemo() {
  try {
    let v = await Promise.reject("Fail!");
  } catch (e) {
    console.log("Error:", e);
  }
}
errorDemo();
    

Common Mistakes

async function parallel() {
  let [a, b] = await Promise.all([
    fetch(url1),
    fetch(url2)
  ]);
}
    
Practice: Try writing async functions that use multiple awaits, handle errors, and work with real API calls.