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 trialMatthew Hargraves
1,487 Pointsreturning null or not setting the correct output.
I am trying to make and alexa skill that reads an API that I have created . The API is working fine and returning
{
"_id": "5a4523104494060cf097c1ad",
"description": "Sprinting",
"date": "2017-12-29"
}
I have the following code
'getNext': function() {
var url = '***API ADDRESS*** ';
var text = "The session will be";
https.get(url, function(response) {
var body = '';
response.on('data', function(x) {
body += x;
});
console.log("a" + text);
response.on('end', function() {
var json = JSON.parse(body);
text += json.description;
console.log("b" + text);
this.emit(":tell", text);
});
console.log("c " + text);
});
console.log("d" + text);
// this.emit(":tell", text);
} Which console outputs
2017-12-29T09:33:47.493Z dThe session will be
2017-12-29T09:33:47.951Z aThe session will be
2017-12-29T09:33:47.952Z c The session will be
2017-12-29T09:33:48.011Z bThe session will beSprinting
However this is returning null for the this.emit function as it is.
If I comment that out and uncomment the other I get a <speak> The session will be</speak> returned.
I think is something to do with scope but cant pin it down as to why the text is correct in log b but not in d. if I cant use this.emit in the resonoce.on('end') then I need a way of getting the information out of there to use at the very end.
1 Answer
Steven Parker
231,271 PointsIt's not scope but timing. The "d" message prints when the "getNext" method is called. Then both "a" and "c" print when the request (get) callback runs. Finally, "b" prints only after the request has completed, the JSON has been parsed, and "text" has been appended with the "description" field data.