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 trialCarlos Casciano
10,459 PointsWhy does response on the function refers to the https get?
Hi!
In the code below, I don´t understand why 'res' in the anonymous function refers to the data inside the https we are getting, what is the logic here? Is it a simple response from the server that I am receiving? Is it a keyword in this case?
https.get("https://teamtreehouse.com/" + username + ".json", function(res){
console.dir(res.statusCode);
})
Ty,
1 Answer
Casey Ydenberg
15,622 PointsBasically, .get
is a function which accepts two parameters. The second parameter is a callback function that explains what to do when a response is received. Whenever Node receives a response, it will call the function that was passed to it when .get
is run.
By definition, the first parameter passed to that callback will be the response from the remote server. You can name it whatever you like: replace res
with foo
in the code above and it will still work.
Now you might be wondering, why doesn't https.get
just return the response from the server? In PHP you can just go
<?php
$res = file_get_contents('https://whatever');
?>
which looks a lot cleaner.
This is Node's asynchronous nature. The Node interpreter can't just wait at a specific line of code until it gets a response from somewhere else. So https.get
can't just return a value (Well it can, but not a value that means what you think it does) because it won't have a value a the time that the request is fired off. To get around this, you don't expect a value, you pass in a function that explains what to do when the response comes back.