简体   繁体   中英

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM