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

Steve Fau
Steve Fau
5,621 Points

Declaring the callback separately doesn't work.

The beginning of the code for reference

const astrosUrl = 'http://api.open-notify.org/astros.json';
const wikiUrl = 'https://en.wikipedia.org/api/rest_v1/page/summary/';
const peopleList = document.getElementById('people');
const btn = document.querySelector('button');

// Make an AJAX request
function getJSON(url, callback) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onload = () => {
        if(xhr.status === 200) {
        let data = JSON.parse(xhr.responseText);
        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>
  `;
}

What is the difference between

btn.addEventListener('click', (event) => { 
    getJSON(astrosUrl, (json) => {
        json.people.map( person => getJSON(wikiUrl + person.name, generateHTML))
    })
    event.target.remove()
})

and

function createHTMLelements(json) {
    json.people.map( person => getJSON(wikiUrl + person.name), generateHTML)
}

btn.addEventListener('click', (event) => { 
    getJSON(astrosUrl, createHTMLelements)
    event.target.remove()
})

The first one generates the HTML as expected. The other throws a Uncaught TypeError: callback is not a function which is referring to the return callback(data) in the getJSON() function

1 Answer

Simon Coates
Simon Coates
4,075 Points

Your brackets:

json.people.map( person => getJSON(wikiUrl + person.name, generateHTML))

and

json.people.map( person => getJSON(wikiUrl + person.name), generateHTML)

In the second one, you're calling getJSON with a URL, but not a callback.

Steve Fau
Steve Fau
5,621 Points

Omg I see.. it's always a typo :D

Idk how I managed to do this, I literally copy-pasted the line of code.

Thanks Simon.