我已根据此示例为Alexa创建了一项简单的技能:https://github.com/alexa/skill-sample-nodejs-fact/blob/en-US/lambda/custom/index.js
现在,我希望脚本能够在调用 GetNewFactIntent 时在不同的服务器上记录某些内容。
这就是我尝试做的事情,但是这个存在问题,而这与 http.get 回调中的情况不同。
'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);
});
},
上面的示例中需要替换这个才能使其正常工作?
答案 0 :(得分:1)
this
不会是您的想法,因为您处于回调函数的上下文中。有两种可能的解决方案:
this
变量:
function () { ... }
- > () => { }
。var self = this;
,然后用您的this
变量替换回调中的self
。示例:
function getStuff () {
var self = this;
http.get (..., function () {
// Instead of this, use self here
})
}
有关详细信息,请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this