使用 Lambda 从 Alexa 技能获取空响应
Getting null responce from Alexa skill using Lambda
我正在尝试使 alexa 技能读取我创建的 API。 API 工作正常并返回
{
"_id": "5a4523104494060cf097c1ad",
"description": "Sprinting",
"date": "2017-12-29"
}
我有以下代码
'getNext': function() {
var url = '***API ADDRESS*** ';
var text = "The session will be";
https.get(url, function(response) {
var body = '';
response.on('data', function(x) {
body += x;
});
console.log("a" + text);
response.on('end', function() {
var json = JSON.parse(body);
text += json.description;
console.log("b" + text);
this.emit(":tell", text);
});
console.log("c " + text);
});
console.log("d" + text);
// this.emit(":tell", text);
}
哪个控制台输出
2017-12-29T09:33:47.493Z dThe session will be
2017-12-29T09:33:47.951Z aThe session will be
2017-12-29T09:33:47.952Z c The session will be
2017-12-29T09:33:48.011Z bThe session will beSprinting
然而,这将按原样为 this.emit 函数返回 null。
如果我注释掉那个并取消注释另一个,我会得到一个
<speak> The session will be</speak>
返回。
我认为这与范围有关,但无法确定为什么日志 b 中的文本正确但 d 中的文本不正确。如果我不能在 resonoce.on('end') 中使用 this.emit,那么我需要一种从那里获取信息以在最后使用的方法。
您卡住的原因是异步函数。 https.get
是一个异步函数,意味着代码将继续执行,当 https.get returns 响应时,回调函数将被执行。理想情况下,无论您想对响应做什么,都应该在回调函数内。
您的文本变量的原始值为The session will be
。然后你执行 https.get
并且因为它是异步的,将移动到执行 https.get
之后的其他代码行并执行 console.log("d" + text);
文本的值仍然不变并打印旧值。现在 https.get
returns 成功响应并触发回调,现在文本值已更改,因此 console.log("b" + text);
看到新值
我正在尝试使 alexa 技能读取我创建的 API。 API 工作正常并返回
{
"_id": "5a4523104494060cf097c1ad",
"description": "Sprinting",
"date": "2017-12-29"
}
我有以下代码
'getNext': function() {
var url = '***API ADDRESS*** ';
var text = "The session will be";
https.get(url, function(response) {
var body = '';
response.on('data', function(x) {
body += x;
});
console.log("a" + text);
response.on('end', function() {
var json = JSON.parse(body);
text += json.description;
console.log("b" + text);
this.emit(":tell", text);
});
console.log("c " + text);
});
console.log("d" + text);
// this.emit(":tell", text);
}
哪个控制台输出
2017-12-29T09:33:47.493Z dThe session will be
2017-12-29T09:33:47.951Z aThe session will be
2017-12-29T09:33:47.952Z c The session will be
2017-12-29T09:33:48.011Z bThe session will beSprinting
然而,这将按原样为 this.emit 函数返回 null。
如果我注释掉那个并取消注释另一个,我会得到一个
<speak> The session will be</speak>
返回。
我认为这与范围有关,但无法确定为什么日志 b 中的文本正确但 d 中的文本不正确。如果我不能在 resonoce.on('end') 中使用 this.emit,那么我需要一种从那里获取信息以在最后使用的方法。
您卡住的原因是异步函数。 https.get
是一个异步函数,意味着代码将继续执行,当 https.get returns 响应时,回调函数将被执行。理想情况下,无论您想对响应做什么,都应该在回调函数内。
您的文本变量的原始值为The session will be
。然后你执行 https.get
并且因为它是异步的,将移动到执行 https.get
之后的其他代码行并执行 console.log("d" + text);
文本的值仍然不变并打印旧值。现在 https.get
returns 成功响应并触发回调,现在文本值已更改,因此 console.log("b" + text);
看到新值