9

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); } 
0

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.