Preparation
πŸ’‘ ⏐ JavaScript Questions
19. Async/await

Async/await

The async/await syntax is a special syntax created to help you work with promise objects. It makes your code cleaner and clearer.

How Promises Work

Promises are objects representing the eventual completion or failure of an asynchronous operation. They have three states: pending, fulfilled, or rejected. Here's how they work:

const myPromise = new Promise((resolve, reject) => {
  // Asynchronous operation
  setTimeout(() => {
    const data = { message: "Promise resolved!" };
    resolve(data); // Resolve the Promise with data
    // reject(new Error("Promise rejected!")); // Alternatively, reject the Promise
  }, 1000); // Simulating a delay of 1 second
});
 
myPromise
  .then((data) => {
    console.log(data); // Output: { message: "Promise resolved!" }
  })
  .catch((error) => {
    console.error(error); // Handle errors
  });

Await

await is an operator used inside async functions to wait for a Promise to resolve. It can only be used inside async functions. It pauses the execution of the async function until the Promise is settled (fulfilled or rejected).

async function fetchData() {
  try {
    const data = await myPromise;
    console.log(data); // Output: { message: "Promise resolved!" }
  } catch (error) {
    console.error(error); // Handle errors
  }
}
 
fetchData();

Async

async is a keyword used to define asynchronous functions. An async function always returns a Promise. Inside an async function, you can use the await keyword to wait for other async operations to complete.

async function fetchData() {
  try {
    const data = await myPromise;
    console.log(data); // Output: { message: "Promise resolved!" }
  } catch (error) {
    console.error(error); // Handle errors
  }
}
 
fetchData();

Async/Await vs. .then() Block

Async/Await and .then() are both used to handle asynchronous operations. Here's a comparison:

// Async/Await
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
 
// .then() Block
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error fetching data:', error));

Real Example with fetch()

Here's a real-world example using fetch() to make an HTTP request and handle the response using Async/Await:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
 
fetchData()
  .then(data => {
    console.log(data); // Process fetched data
  })
  .catch(error => {
    console.error(error); // Handle errors
  });

6 Important Points about Async/Await

  1. Simplicity: Async/Await simplifies asynchronous code, making it easier to read and write.
  2. Sequential Execution: Async/Await allows you to write asynchronous code in a sequential manner, improving code readability.
  3. Error Handling: Error handling with Async/Await is straightforward using try-catch blocks.
  4. Promise-Based: Async/Await is built on top of Promises and works seamlessly with existing Promise-based code.
  5. Syntactic Sugar: Async/Await is syntactic sugar over Promises, providing a cleaner syntax for asynchronous operations.
  6. Backward Compatibility: Async/Await is supported in modern JavaScript environments and can be transpiled for backward compatibility.

Error Handling with try/catch

Async/Await simplifies error handling with try-catch blocks:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
    throw error; // Re-throwing the error for further handling
  }
}

Final Thoughts on Async/Await

Async/Await is a powerful feature in modern JavaScript that simplifies asynchronous programming. It enhances code readability, improves error handling, and makes asynchronous code more approachable for developers. Understanding Async/Await is essential for writing clean, maintainable, and efficient asynchronous code.