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?

6
  • 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 Commented Aug 9, 2021 at 6:13
  • 2
    try in this way const Data = await fetchData(); Commented Aug 9, 2021 at 6: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() Commented Aug 9, 2021 at 6:16
  • 2
    Well, then it's time to useState and useEffect ... However before that I'd recommend to get familiar with asynchrony in JS. Commented Aug 9, 2021 at 6: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 Commented Aug 9, 2021 at 6:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.