[英]Getting null responce from Alexa skill using Lambda
我正在嘗試制作讀取我創建的 API 的 alexa 技能。 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 返回響應時,將執行回調函數。 理想情況下,無論您想對響應做什么,都應該在回調函數中。
您的文本變量的原始值是The session will be
. 然后你執行https.get
並且因為它是異步的,將在https.get
之后執行其他代碼https.get
並執行console.log("d" + text);
text 的值仍然不變並打印舊值。 現在https.get
返回成功響應並觸發回調,現在文本值已更改,因此console.log("b" + text);
看到新值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.