Sobes.tech
Junior — Middle

How do the async/await constructs differ from Promise when working with asynchronous code in JavaScript?

sobes.tech AI

Answer from AI

Promise is an object representing the result of an asynchronous operation, which can be fulfilled or rejected in the future. It allows registering handlers via then() and catch() methods.

async/await is syntactic sugar over Promise, enabling writing asynchronous code in a synchronous style, making it more readable and easier to debug.

Main differences:

  • Promise requires chaining then/catch for handling results and errors.
  • async/await allows using the await keyword to wait for the Promise result inside an asynchronous function.

Example:

// Promise
fetch(url)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

// async/await
async function fetchData() {
  try {
    const response = await fetch(url);
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
fetchData();

Thus, async/await simplifies working with Promise, making the code more linear and understandable.