0

I am new to this whole async function concept. Here is the function that I want to use:

async function fetchData() {
    try {
      const resultRes = await fetch("https://www.breakingbadapi.com/api/characters?category=Better+Call+Saul");
      const result = await resultRes.json();
      
      return result;
    } catch (error) {
      console.error(error);
    }
}

And this is what function call looks like:

const Data = fetchData();

Now I want to console.log(Data) with the array that is returned but intead it shows as a promise object. How should I use this function as using it with .then messes up my whole app as the containing file is a react component?

MiSiMa49
  • 11
  • 1
  • 2
  • an async function, by its definition, returns a Promise ... try `fetchData().then(Data => console.log(Data))` ... or `const Data = await fetchData()` if you can - i.e. top level of a module or inside an `async function` – Bravo Aug 09 '21 at 06:13
  • 2
    try in this way `const Data = await fetchData();` – Suneel Kumar Aug 09 '21 at 06:13
  • but the containing function is not async and making it async makes that function return a promise which doesn't seem to work in reactDOM.render() – MiSiMa49 Aug 09 '21 at 06:16
  • 2
    Well, then it's time to `useState` and `useEffect` ... However before that I'd recommend to get familiar with asynchrony in JS. – Jonas Wilms Aug 09 '21 at 06:17
  • asynchrony is like a virus - it infects everything it touches, and there is no cure. if you think of asynchrony as giving you a result at some undetermined time in the future, you'll soon understand that it can't be "predicted" - unless code can time travel - which it can't – Bravo Aug 09 '21 at 06:20
  • I do understand in theory how asynchrony is working but when trying to work with it in actual code is proving very hard – MiSiMa49 Aug 09 '21 at 06:21

0 Answers0