2

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?

1
  • I can't see an immediate problem with that code. Can you add additional information about exactly how it is failing? More context is needed. Commented Nov 11, 2017 at 11:06

1 Answer 1

1

this will not be what you think it is, because you are in the context of the callback function. There are two possible solutions:

  1. Use an arrow function instead. An arrow function preserves the this variable of the scope it is being used in: function () { ... } -> () => { }.
  2. Declare 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

Sign up to request clarification or add additional context in comments.

2 Comments

I tried with var that = this before but couldn't get it to work but arrow function did the trick. I didn't know that it preserves this variable of the scope so it is good to know this. Many thanks.
Happy to see you could fix your problem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.