Sobes.tech
Junior — Middle

What is the difference between using the .then method and using the await operator when working with promises?

sobes.tech AI

Answer from AI

The .then method and the await operator are both used for working with promises, but they differ in syntax and style of handling asynchronous code:

  • .then is a promise method that takes a callback to handle the result or error. It allows chaining calls, but the code can become less readable with many nested .then calls.

  • await is an operator that can only be used inside an asynchronous function (async). It pauses the execution of the function until the promise is resolved, allowing writing asynchronous code in a synchronous style, which improves readability and simplifies error handling with try/catch.

Example with .then:

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

Example with 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, await makes asynchronous code more linear and easier to read, while .then is a more traditional way of working with promises.