Please assess JSON test

It wasn’t easy. I would appreciate your suggestions/comments. Thanks!

Hi @Mikhail

Great work! Your code is flawless.
Do you also know the answer to the additional question?

Why are the para1.textContent = motherInfo; and para2.textContent = kittenInfo; lines inside the displayCatInfo() function, and not at the end of the script? This has something to do with async code.

See you,
Michael

1 Like

because JavaScript is single threaded?)

Not quite.
fetch() is asynchronous, which means after calling it, JS will continue with the rest of the code until the answer from the server arrives. displayCatInfo() will be called after the answer from the server arrives. So we have all the necessary data to populate the two textContents:

  • fetch request
  • fetch response
  • displayCatInfo called
  • textContent populated

If the two textContents were outside, they would be assigned immediately after the fetch() call when there’s still no answer from the server:

  • fetch request
  • :warning: textContent populated with default values from the start
  • fetch response
  • displayCatInfo called
  • changes to motherInfo and kittenInfo don’t matter, because the textContent assignments already happened before

Does that make sense?

1 Like

The function waits for a response from Fetch and only then assigns variables within itself with the received data after .parse? Do I get it right?

Thank you for your time!

Yes. And the important thing is, while waiting it continues with the rest of the code outside fetch() and displayCatInfo(). In your CodePen that’s the last two lines (L45, L46). So, the paragraphs get appended immediately, but there content is added after the response from fetch() returns.

I’m glad I could help. :slightly_smiling_face:

1 Like