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 Stepping Through Async Code

Manoj Gurung
Manoj Gurung
5,313 Points

why is this returning undefined

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) { const xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = () => { if(xhr.status === 200) { let data = JSON.parse(xhr.responseText); return data; } }; xhr.send(); }

var dataP=getJSON(astrosUrl); console.log(dataP);

1 Answer

Robert Manolis
Robert Manolis
Treehouse Guest Teacher

Hi Manoj Gurung, I can't say for certain without running the code myself, but if you're asking why the log statement at the end is printing undefined to the console, I would say it probably has to do with the asynchronous nature of making those http requests. At the moment the log statement runs, the dataP variable is undefined. You can use promises, async/await or callbacks to delay the printing of the log statement till after the requests/response cycle resolves. Or you could even just use a setTimeout function to delay the printing for a bit, but that is a pretty hacky way to go about it, and not really something you would want to get in the habit of doing. :smiley:

Hope that helps! :thumbsup: