5

The following pieces of code are giving me the same result. What is the difference between the use of .then and async/await to fetch data?

// Code 1

function fetchData() {
  fetch(url)
      .then(response => response.json())
      .then(json => console.log(json))
}



// Code 2

async function fetchData() {
  const response = await fetch(url);
  const json = await response.json();
  console.log(json);
}
Tugay
  • 2,057
  • 5
  • 17
  • 32
Leandro
  • 51
  • 1
  • 2

1 Answers1

4

Async and await is just syntactic sugar. They do the same thing as “then” but the await syntax is generally considered preferable since it allows to avoid nesting then statements and is arguably easier to read.

Vlad L
  • 1,544
  • 3
  • 6
  • 20