search

Home  >  Q&A  >  body text

Using Async/Await with .then()

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粉545682500P粉545682500293 days ago480

reply all(1)I'll reply

  • P粉426906369

    P粉4269063692024-02-04 11:38:47

    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.

    reply
    0
  • Cancelreply