es6

Chapter 12: async/await in JavaScript – Clean and Simple Asynchronous Code

Chapter 12: JavaScript async/await – Simplified Asynchronous Programming

async/await is a modern way to handle asynchronous operations in JavaScript. It is built on top of Promises and provides a more readable, sequential-looking structure for writing asynchronous code — avoiding the clutter of .then() and .catch() chaining.

🚀 The async Keyword

The async keyword is used to declare a function as asynchronous. This function always returns a Promise, regardless of whether it explicitly returns one or not.


async function greetUser() {
  console.log('This is an async function.');
  return 'Done';
}

greetUser();  // Returns a Promise
  

To get the result from the returned Promise, you can use .then():


greetUser().then(response => {
  console.log(response); // Done
});
  

⏳ The await Keyword

The await keyword pauses the execution of an async function until the Promise is settled. It can only be used inside async functions.


let promise = new Promise(resolve => {
  setTimeout(() => resolve("Task Completed"), 2000);
});

async function asyncFunc() {
  let result = await promise;
  console.log(result);           // Task Completed (after 2 seconds)
  console.log('Next Message');   // Executes after promise resolves
}

asyncFunc();
  

🛠 Error Handling with try/catch

You can handle errors inside async functions using try...catch blocks just like synchronous code.


let promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Promise resolved"), 2000);
});

async function asyncFunc() {
  try {
    let result = await promise;
    console.log(result);
  } catch (error) {
    console.log('Error:', error);
  }
}

asyncFunc();
  

🌐 Real Example: Fetching API Data Using async/await


async function fetchPosts() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    if (!response.ok) {
      throw new Error('Failed to fetch posts');
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching posts:', error);
    throw error;
  }
}

function processPosts(posts) {
  console.log('Fetched posts:', posts);
}

function handleError(error) {
  console.error('An error occurred:', error);
}

async function main() {
  try {
    const posts = await fetchPosts();
    processPosts(posts);
  } catch (error) {
    handleError(error);
  }
}

main();
  

This structure makes asynchronous code look and behave much more like synchronous code, improving readability and maintainability.

📘 Assignments: Practice async/await

  1. Create an async function that returns a string and log its result using .then().
  2. Make an async function that waits for a Promise resolving in 2 seconds and prints both the result and a follow-up message.
  3. Wrap your await call inside a try...catch and simulate a Promise.reject() to test error handling.
  4. Write a function that fetches data from an API (e.g., JSONPlaceholder) and logs the first post title using await.
  5. Compare and rewrite an existing .then() chain using async/await syntax.

📌 Summary

  • async declares an asynchronous function and ensures it returns a Promise.
  • await pauses the function until the Promise resolves or rejects.
  • Helps avoid callback hell and improves readability of async logic.
  • Works great with API calls and long-running operations like file uploads or timeouts.
  • Use try/catch with await for robust error handling.

Leave a Reply

Your email address will not be published. Required fields are marked *