The Journey of #100DaysOfCode (Baqer_Qabalan)

Day 12: Asynchronous JavaScript with Async/Await

:arrows_counterclockwise: What is Asynchronous JavaScript?

Asynchronous JavaScript allows you to perform long-running tasks, like fetching data from an API, without blocking the main thread. This makes your web applications more responsive and user-friendly.

:blue_book: Why Use Async/Await?

  • Simplified Syntax: Async/await provides a cleaner and more readable way to work with promises compared to chaining .then() and .catch() methods.
  • Error Handling: Easier error handling using try...catch blocks.
  • Sequential Execution: Allows for writing asynchronous code that looks and behaves like synchronous code.

:sparkles: How to Use Async/Await

  1. Defining an Async Function

An async function is declared using the async keyword before the function definition:

async function fetchData() {
  // Code inside here is asynchronous
}
  1. Using await

The await keyword pauses the execution of the async function until the promise is resolved:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
  1. Handling Errors

With async/await, you can handle errors using a try...catch block:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

100daysofcode lebanon-mug

3 Likes