Javascript Alexa nodejs从Amazon Lambda访问url
基于这个例子,我为Alexa创建了一个简单的技能: 现在,我想让脚本在调用GetNewFactIntent时在不同的服务器上记录一些东西 这正是我试图做的,但有一个问题,这不是它应该在http.get回调Javascript Alexa nodejs从Amazon Lambda访问url,javascript,node.js,aws-lambda,alexa,alexa-skills-kit,Javascript,Node.js,Aws Lambda,Alexa,Alexa Skills Kit,基于这个例子,我为Alexa创建了一个简单的技能: 现在,我想让脚本在调用GetNewFactIntent时在不同的服务器上记录一些东西 这正是我试图做的,但有一个问题,这不是它应该在http.get回调 'GetNewFactIntent': function () { //var thisisit = this; http.get("http://example.com", function(res) { //console.log("Got response: " + res.stat
'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);
});
},
在上面的示例中,需要用什么来替换它才能工作?
这将不是您所认为的,因为您处于回调函数的上下文中。有两种可能的解决方案:
改用箭头函数。箭头函数保留其使用范围的变量:
函数(){…}
->()=>{}
声明var self=this
在回调外部,然后将回调内部的this
替换为self
变量
例如:
function getStuff () {
var self = this;
http.get (..., function () {
// Instead of this, use self here
})
}
有关更多信息,请参阅:我看不出该代码存在即时问题。您是否可以添加有关其故障原因的详细信息?需要更多的上下文。我以前尝试过var that=this,但无法让它工作,但箭头函数成功了。我不知道它保留了这个作用域变量,所以很高兴知道这一点。非常感谢。很高兴看到你能解决你的问题!