Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Murilo de Melo
Murilo de Melo
13,962 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,842 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.