gpt4 book ai didi

javascript - Alexa nodejs 从 Amazon Lambda 访问 url

转载 作者:行者123 更新时间:2023-11-29 23:31:20 25 4
gpt4 key购买 nike

我基于这个例子为 Alexa 创建了一个简单的技能:https://github.com/alexa/skill-sample-nodejs-fact/blob/en-US/lambda/custom/index.js

现在,我希望脚本在调用 GetNewFactIntent 时在不同的服务器上记录一些内容。

这是我正在尝试做的事情,但是 this 有问题,这不是 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);
});
},

在上面的示例中需要用什么this替换它才能工作?

最佳答案

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

关于javascript - Alexa nodejs 从 Amazon Lambda 访问 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47236996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com