Alexa nodejs 从 Amazon Lambda 访问 url
Alexa nodejs accessing url from Amazon Lambda
我根据这个例子为 Alexa 创建了一个简单的技能:https://github.com/alexa/skill-sample-nodejs-fact/blob/en-US/lambda/custom/index.js
现在,我希望脚本在调用 GetNewFactIntent 时在不同的服务器上记录一些内容。
这是我正在尝试做的事情,但是 this 有问题,这不是 http.get[ 中应该出现的问题=25=]回调。
'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);
});
},
在上面的示例中需要用什么 this 来替换它才能工作?
this
不会是你想的那样,因为你处在回调函数的上下文中。有两种可能的解决方案:
- 改用箭头函数。箭头函数保留它正在使用的范围的
this
变量:
function () { ... }
-> () => { }
.
- 在回调外部声明
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
我根据这个例子为 Alexa 创建了一个简单的技能:https://github.com/alexa/skill-sample-nodejs-fact/blob/en-US/lambda/custom/index.js
现在,我希望脚本在调用 GetNewFactIntent 时在不同的服务器上记录一些内容。
这是我正在尝试做的事情,但是 this 有问题,这不是 http.get[ 中应该出现的问题=25=]回调。
'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);
});
},
在上面的示例中需要用什么 this 来替换它才能工作?
this
不会是你想的那样,因为你处在回调函数的上下文中。有两种可能的解决方案:
- 改用箭头函数。箭头函数保留它正在使用的范围的
this
变量:function () { ... }
->() => { }
. - 在回调外部声明
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