I’m a bit confused with the async/await concept, especially when it comes to using it compared to .then() in a function.
I’m currently playing around with a basic React application and fetching some data in a useEffect
I was wondering, as a fetch
returns a Promise
why do I not need to mark anything as async
or await
when doing the following example:
useEffect(() => {
fetch("whatever").then(res => console.log(res));
}, [])
but when I choose to do await
I would need to wrap the code in an async
function
useEffect(() => {
// error, needs to be in an async function
const res = await fetch("whatever");
},[])
I guess my question is really what is the difference between chaining with .then()
vs using async
await
and why doesnt .then()
require me to await anything, even if the fetch returns a promise?
Thanks
2
Answers
Async/await is "just" syntactic sugar. It allows you to write nice asynchronous code and it looks like it is synchronous, it is easier to follow the control flow, especially when you have multiple functions to wait for. If you use .then() .catch() you are in the same callback hell as you where before there where promises.
However, you can only use async/await if the function is async.
useEffect()
seems to be a bad example to demonstrate async/await, but in general, when you use.then()
, basically a callback is called, when the result is available, hence you do not have to await anything.To add to @HEllRZA, both then() and async/await can be used to handle promises in JavaScript. Then() is a method that takes a callback function as a parameter and allows you to chain multiple then() methods to handle the response in a sequence. Async/await is a new way of writing asynchronous code in JavaScript.