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 Node.js Basics 2017 Create a Command Line Weather Application Handling Errors - Solution

Pete Lower
Pete Lower
17,225 Points

Unable to return parsed JSON from w/in response on end call.

When trying to return the JSON object, I get 'undefined'. I believe this is an asynchronicity (as apposed to scope) problem but I am unsure how to fix it.

Here is my function

function connectToAPI(url, location) {

try {

    const request = http.get(url, response => { // node http get method and callback
        if(response.statusCode === 200) {
            let json = '';

            response.on('data', function(data) { // Read the data
                json += data;
            });

            response.on('end', () => { // node http on end function and callback, Parse the data
                if ( !JSON.parse(json).response.error && !JSON.parse(json).response.results ) { // if not city not found or search results page
                    let jsonParsed = JSON.parse(json);
                    let weatherInfo = createCurrentWeatherObject(jsonParsed);
                    print.printMessageToConsole(weatherInfo) // print to console
                } else if (JSON.parse(json).response.results) {
                    print.printError("Multiple Cities Found, Enter Full State Name");
                } else {
                    print.printError("Location Not Found");
                }
            });
        } else {
            const statusCodeError = new Error(`There was an error getting the weather for ${location} (${http.STATUS_CODES[response.statusCode]})`);
            print.printError(statusCodeError);
        }
    });

    request.on('error', error => { console.error(`Problem With Request: ${error.message}`); });

} catch (error) {
    print.printError(error);
}

}

Thanks!

Javier Alvarado
Javier Alvarado
16,060 Points

What exactly gets printed out when you run this? Does the console just say 'undefined'?

1 Answer

David Kanwisher
David Kanwisher
9,751 Points

I would comment out your if and if else statements within your respond.on end function. Then console.log(JSON.parse(json)). If it works, then you can work from there. If it doesn't work, you have an error occurring earlier and you can work from there. It's hard to debug without knowing which API you're using/seeing all of your code.

As far as asynchronicity, your code doesn't run until it gets a response, and your "end" doesn't run until your data is finished. I don't think it's a problem with asynchronicity.