What is await and how does it work?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Medium
#JavaScript #Functions #Asynchronicity #JS Basics

Brief Answer

The await keyword is used inside asynchronous functions (with [async]) to wait for a Promise to complete. It “stops” function execution until the Promise completes, and returns the Promise result. This makes asynchronous code look like synchronous code.

// Asynchronous function with await
async function fetchData() {
  console.log('Starting download...');
  const response = await fetch('/api/data'); // Wait for response
  const data = await response.json();        // Wait for parsing
  return data;
}
 
// Usage
fetchData().then(result => console.log(result));

Full Answer

The [await] keyword is like an airport dispatcher telling a plane: “Wait until the runway is ready, then you can take off”. [await] makes code wait for an asynchronous operation to complete without blocking the entire site! ✈️

What is await

The [await] keyword can only be used inside asynchronous functions (with [async]). It waits for a Promise to complete and returns its result:

Simple Examples

Basic await Usage

async function example() {
  console.log('Start');
  
  // Wait 2 seconds
  await new Promise(resolve => setTimeout(resolve, 2000));
  
  console.log('2 seconds passed');
  return 'Done';
}

Working with Network

async function getUserData() {
  try {
    const response = await fetch('/api/user');
    const userData = await response.json();
    return userData;
  } catch (error) {
    console.log('Loading error:', error);
  }
}

How await Works

Step-by-Step Execution

async function stepByStep() {
  console.log('1. Start');
  
  const result1 = await Promise.resolve('First result');
  console.log('2.', result1);
  
  const result2 = await Promise.resolve('Second result');
  console.log('3.', result2);
  
  console.log('4. End');
}
 
stepByStep();
// Output:
// 1. Start
// 2. First result
// 3. Second result
// 4. End

Doesn’t Block Entire Code

async function asyncTask() {
  console.log('Task started');
  await new Promise(resolve => setTimeout(resolve, 3000));
  console.log('Task completed');
}
 
console.log('1. Start');
asyncTask(); // Starts execution, but doesn't block
console.log('2. Continue'); // Executes immediately
console.log('3. End'); // Executes immediately
// After 3 seconds: 'Task completed'

When to Use await

For Simplifying Asynchronous Code

// Instead of .then() chains
// fetch('/api/data')
//   .then(response => response.json())
//   .then(data => processData(data))
//   .then(result => console.log(result))
//   .catch(error => console.log(error));
 
// With await code is cleaner
async function handleData() {
  try {
    const response = await fetch('/api/data');
    const data = await response.json();
    const result = processData(data);
    console.log(result);
  } catch (error) {
    console.log('Error:', error);
  }
}

For Sequential Operations

async function sequentialOperations() {
  const user = await fetchUser();
  const posts = await fetchUserPosts(user.id);
  const comments = await fetchPostComments(posts[0].id);
  return { user, posts, comments };
}

Common Mistakes

Using Outside async Functions

// ❌ Error — await outside async function
// function bad() {
//   const result = await somePromise(); // SyntaxError!
// }
 
// ✅ Correctly
async function good() {
  const result = await somePromise(); // Works!
}

Forgetting Error Handling

// ❌ Error — error not handled
// async function risky() {
//   const data = await fetch('/api/data');
//   // If fetch fails, error will "fall" up
// }
 
// ✅ Correctly — error handling
async function safe() {
  try {
    const data = await fetch('/api/data');
  } catch (error) {
    console.log('Error:', error);
  }
}

Simple Rules

  1. await — waits for Promise completion and returns result ⏱️
  2. Only in async — can be used only inside async functions 🚫
  3. Non-blocking — stops only current function, not entire code ⚡
  4. Readability — makes asynchronous code look like synchronous 📖
  5. Errors — use try/catch for error handling ⚠️

The [await] keyword is a powerful tool for working with asynchronous operations, making code more readable and understandable! 💪


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪