Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Asynchronous Programming with JavaScript Asynchronous JavaScript with Callbacks Implement a Callback

Murilo de Melo
Murilo de Melo
14,456 Points

Why do we need to parse JSON for every person in the list people? Ist it not possible/more efficient to parse it once?

For every person in the map, the second getJSON() function call in the event listener parse JSON to JS. Despiting have learned in previous JS tutorials that is not a good idea to include global variables in functions to reduce coupling (dependeability), isn't it possible to parse the map/list just once and retrieve the data from it in order to reduce the processing effort?

(...)
// Make an AJAX request
function getJSON(url, callback) {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.onload = () => {
    if(xhr.status === 200) {
      console.log('Step 3: Parsin JSON to JS and callback');
      let data = JSON.parse(xhr.responseText);
      console.log(data);
      return callback(data);
    }
  };
  xhr.send();
}

// Generate the markup for each profile
function generateHTML(data) {

  const section = document.createElement('section');
  peopleList.appendChild(section);
  section.innerHTML = `
    <img src=${data.thumbnail.source}>
    <h2>${data.title}</h2>
    <p>${data.description}</p>
    <p>${data.extract}</p>
  `;
  console.log(`Step 4: creating DOM for ${data.title}`);
}

btn.addEventListener('click', () => {
   console.log('Step 1: Button clicled');
   getJSON(astrosUrl, (json) => {
      json.people.map(person => {
         console.log('Step 2: Iterating over people');
         getJSON(wikiUrl + person.name, generateHTML);
   });
});

1 Answer

Doron Geyer
seal-mask
.a{fill-rule:evenodd;}techdegree
Doron Geyer
Full Stack JavaScript Techdegree Student 13,897 Points

Murilo de Melo , from what I can see here you wouldnt be able to because for you to change how it parses the second time you would have to change the way your getJson() function is built out and works. That would mean you cannot pass it back in as is and would have to create a completely new callback function.