Sobes.tech
Junior

What are async/await and what are they used for?

sobes.tech AI

Answer from AI

Async/await is syntactic sugar over promises in JavaScript, allowing you to write asynchronous code in a synchronous style.

They are needed for:

  1. Improving code readability: Asynchronous code becomes more sequential and understandable, avoiding "callback hell".
  2. Simplifying error handling: try...catch blocks work with async/await just like with synchronous code.
  3. Easier debugging: The flow of execution is more apparent.

Key points:

  • A function marked with async always returns a promise.
  • The await operator can only be used inside an async function. It pauses the execution of the async function until the promise it is applied to is fulfilled or rejected, then returns the result or throws an error.
// Example of using async/await
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data'); // Wait for the fetch promise to resolve
    const data = await response.json(); // Wait for the response.json() promise
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error); // Error handling
  }
}

fetchData(); // Call the asynchronous function
What are async/await and what are they used for… - sobes.tech