Alexa nodejs从Amazon Lambda访问URL

时间:2017-11-11 10:40:01

标签: javascript node.js aws-lambda alexa alexa-skills-kit

我已根据此示例为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);
});
},

上面的示例中需要替换这个才能使其正常工作?

1 个答案:

答案 0 :(得分:1)

this不会是您的想法,因为您处于回调函数的上下文中。有两种可能的解决方案:

  1. 请改用箭头功能。箭头函数保留其正在使用的范围的this变量: function () { ... } - > () => { }
  2. 在回调之外声明var self = this;,然后用您的this变量替换回调中的self
  3. 示例:

    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