Reputation: 133
I've created a simple skill for Alexa based on this example: https://github.com/alexa/skill-sample-nodejs-fact/blob/en-US/lambda/custom/index.js
Now, I'd like the script to log something on a different server when GetNewFactIntent is called.
This is what I'm trying to do but have an issue with this which is not what it should be in the http.get callback.
'GetNewFactIntent': function () {
//var thisisit = this;
http.get("http://example.com", function(res) {
//console.log("Got response: " + res.statusCode);
const factArr = data;
const factIndex = Math.floor(Math.random() * factArr.length);
const randomFact = factArr[factIndex];
const speechOutput = GET_FACT_MESSAGE + randomFact;
this.response.cardRenderer(SKILL_NAME, randomFact);
this.response.speak(speechOutput);
this.emit(':responseReady');
}).on('error', function(e) {
//console.log("Got error: " + e.message);
});
},
What this needs to be replaced with in the example above for this to work?
Upvotes: 2
Views: 130
Reputation: 4187
this
will not be what you think it is, because you are in the context of the callback function. There are two possible solutions:
this
variable of the scope it is being used in:
function () { ... }
-> () => { }
.var self = this;
outside of the callback and then replace your this
inside the callback with your self
variable.Example:
function getStuff () {
var self = this;
http.get (..., function () {
// Instead of this, use self here
})
}
For further information, see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Upvotes: 1