Fayza Nawaz Fayza Nawaz - 1 month ago 20
Javascript Question

Accessing 'this' in http request's response | Node.js

I'm working on Alexa skill and using Node.js for writing my lambda function. I'm also using Alexa SDK for handling Alexa's requests and response.
The issue i'm facing is that i'm unable to access "this pointer" in response. Code is as:

var handler = Alexa.CreateStateHandler();
handler['hi'] = function( ) {

console.log("hi intent");

request(url, function (error, response, body) {

const message = "Hello there. Best of luck!";
const reprompt = "Hello there.";

this.response.speak(message).listen(reprompt);
this.emit(':responseReady');
});
};


Error: this.response not found

FYI: handler['hi'] is a listener and is invoked automatically from Alexa. I can access this pointer outside request block.

I read different answers on SO, but none of them is answering my question. Please help, how can i access "this" inside response.

Tom Tom
Answer

Your question is really a javascript question. The js 'this' is different then you might be used to from languages like c/c++, and the problem you are encountering here - accessing 'this' from within a callback - is a common js pitfall so it has already been answered quite well, eg.

How to access the correct `this` / context inside a callback?

Comments