Assessment wanted for JSON skill test and Question on async

const section = document.querySelector('section');

let para1 = document.createElement('p');
let para2 = document.createElement('p');
let motherInfo = 'The mother cats are called ';
let kittenInfo;
const requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/tasks/json/sample.json';

fetch(requestURL)
  .then(response => response.text())
  .then(text => displayCatInfo(text))

function displayCatInfo(catString) {
  let total = 0;
  let male = 0;

// Add your code here
catString = JSON.parse(catString)
for(let i in catString){
if(i == catString.length -1){
motherInfo += `and ${catString[i].name}.`
}else{
motherInfo += `${catString[i].name}, `
}
}

let kittens =[];
for(let i in catString){
kittens = kittens.concat(catString[i].kittens)
}
male = kittens.filter(item => item.gender === 'm').length
kittenInfo = `The total number of kittens is ${kittens.length}, there are ${male}  males and ${kittens.length - male} females`
// Don't edit the code below here!

  para1.textContent = motherInfo;
  para2.textContent = kittenInfo;
}

section.appendChild(para1);
section.appendChild(para2);

Assessment Page

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

Hi @owolagbadavid and welcome back :wave:

Congratulations! You solved the task correctly. :medal_sports:
I especially like the usage of concat() and filter() to count the males.
You can avoid using the same loop twice by moving the concat() line into the other loop and let kittens =[]; before the first loop.

fetch() is an async call. That means it asks for the data at the URL, but doesn’t wait until the JSON arrives. It just continues with the rest of the code. If these two lines were outside the function, they would be executed immediately and the initial values would be assigned to the paragraphes. Later, the JSON will arrive and the function is executes, but the final values of motherInfo and kittenInfo will never be assigned to para1 and para2, because the assignment already happened before.

Does that make it clearer?

Have a nice day,
Michael

Yeah it does
Thanks.

1 Like