2017-11-11 369 views
2

我已经创建了一个基于这个例子Alexa的简单技能访问网址:https://github.com/alexa/skill-sample-nodejs-fact/blob/en-US/lambda/custom/index.jsAlexa的距离的NodeJS亚马逊LAMBDA

现在,我想的脚本来登录一些不同的服务器上,当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不会是你认为的那样,因为你在回调函数的上下文中。有两个可能的解决方案:

  1. 使用箭头函数。一个箭头函数保留了它在其中使用的范围的this变量: function() { ... } - >() => { }
  2. 声明var self = this;以外的回调,然后用你的self变量替换你的this回调。

实施例:

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

+0

我曾尝试过_var that = this_之前,但无法让它工作,但箭头功能做到了。我不知道它保留了范围的_this_变量,所以知道这一点很好。非常感谢。 –

+0

很高兴看到你能解决你的问题! – NikxDa