Sobes.tech
Middle

How to work with asynchronous JavaScript? How does async/await differ from promises?

sobes.tech AI

Answer from AI

Asynchronous JavaScript allows performing operations that take time (such as server requests) without blocking the main thread.

Promises are objects that represent the result of an asynchronous operation and can be in pending, fulfilled, or rejected states. They enable chaining handlers via .then() and .catch().

async/await is syntactic sugar over promises, allowing writing asynchronous code in a more readable manner, similar to synchronous code. An async function always returns a promise, and await pauses the execution of the function until the promise resolves.

Example with promises:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Same with async/await:

async function getData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
getData();

The main difference is that async/await improves readability and simplifies error handling through regular try/catch.

How to work with asynchronous JavaScript? How does… - sobes.tech