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
Chigozie Beluolisa
16,263 PointsHELP ! ! Can't return a Variable in an Anonymous function scope in Node.js
Hello Developers,
Please i am trouble trying to return the variable(profile) in the get(username) function. I have tried setting profile as a global variable but it doesn't seem to work. Please see script below for more details :)
Thanks in anticipation of your feedback !!
//Problem: Can't return variable(profile) in an annonymous function
var http = require("http");
//Print out message
function printMessage(username, badgeCount, points) {
var message = username + " has " + badgeCount + " total badge(s) and " + points + " points in JavaScript";
console.log(message);
}
//Print out error messages
function printError(error){
console.error(error.message);
}
function get(username){
//Connect to the API URL (https://teamtreehouse.com/username.json)
var request = http.get("http://teamtreehouse.com/" + username + ".json", function(response){
var body = "";
//Read the data
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function(){
if(response.statusCode === 200) {
try {
//Parse the data
var profile = JSON.parse(body);
//Print the data
printMessage(username, profile.badges.length, profile.points.JavaScript);
console.log("variable profile in anonymous function scope is",profile);
} catch(error) {
//Parse Error
printError(error);
}
} else {
//Status Code Error
printError({message: "There was an error getting the profile for " + username + ". (" + http.STATUS_CODES[response.statusCode] + ")"});
}
});
});
//Connection Error
request.on("error", printError);
//Can't return variable profile
// variable (profile) is stored in the anonymous function scope
// where the JSON data is parsed
console.log(profile);
return profile;
}
var profile = get("chalkers");
3 Answers
Hugo Paz
15,622 PointsHi Chigozie,
looking at your code, it seems you are not saving the return anywhere.
Try this:
var profile = get("chalkers");
Sean T. Unwin
28,690 PointsIt is failing at line 49, because when you call profile there it is outside the scope of where var profile was declared. This is an example of Encapsulation.
If you move that code to line 31, i.e subtitute the console.log() statement that is already there so it's more descriptive it will output:
// Line 31
// Change
console.log(profile);
// To
console.log("The data in variable profile is",profile);
// I know it's the same thing basically,
// but we're making the output more relatable.
By the way, outputting profile will be quite long and the beginning may get cut off by your console.
Chigozie Beluolisa
16,263 PointsThanks for your answer Sean T. Unwin . it looks like the variable profile is private in the annonymous function. My goal is to make it public so that i can return it at the end of the function call.
Sean T. Unwin
28,690 PointsThe code above I posted is at the end of the function call. I can understand how it doesn't feel like it, but it is because the `response.on('end') happens at the end of the AJAX request.
If you try to do it at the end of the code for the get() function it's not really the end, it's near the beginning sort of since get() is waiting for response object to return.
Lemuel Ambie-Barango
31,559 PointsHi Chigozie,
Since you have a 'try/catch' block. I will suggest that you print and return the profile in the try block and set the profile to nil and return in the catch block so if there's an error it will set the profile as nil and print the error.
try {
//Parse the data
var profile = JSON.parse(body);
//Print the data
printMessage(username, profile.badges.length, profile.points.JavaScript);
console.log(profile);
console.log(username);
//Can't return variable profile
console.log("The data in variable profile is",profile);
return profile;
} catch(error) {
//Parse Error
printError(error)
var profile = ' ';
console.log("The data in variable profile is",profile);
return profile;
}
Sean T. Unwin
28,690 PointsI have edited your post so that the code is more readable.
Please see this thread if you need help posting code snippets.
Chigozie Beluolisa
16,263 PointsChigozie Beluolisa
16,263 PointsThanks HugoPaz for your swift response. I have tried it and it doesn't seem to work. It looks like the variable (profile) in the anonymous function becomes undefined outside the anonymous function scope. So it ends up returning undefined