Using Async/Await with .then()
P粉545682500
P粉545682500 2024-02-03 16:32:02
0
1
479

I'm a little confused by the concept of async/await, especially when compared to .then() in functions.

I'm currently working with a basic React app and getting some data in useEffect

I'm wondering, since fetch returns a Promise, why I don't need to mark anything as async or await when executing the following example :

useEffect(() => {
    fetch("whatever").then(res => console.log(res));
  }, [])

But when I choose to execute await, I 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 actually what is the difference between using .then() vs using async await links and why . then() doesn't require me to wait for anything, even if getting returns a promise? < /p>

Thanks

P粉545682500
P粉545682500

reply all(1)
P粉426906369

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 process responses in sequence. Async/await is a new way of writing asynchronous code in JavaScript.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template