【问题标题】:Getting null responce from Alexa skill using Lambda使用 Lambda 从 Alexa 技能获取空响应
【发布时间】:2018-06-09 18:45:37
【问题描述】:

我正在尝试制作读取我创建的 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,那么我需要一种从那里获取信息以在最后使用的方法。

【问题讨论】:

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


    【解决方案1】:

    卡住的原因是异步函数。 https.get 是一个异步函数,意味着代码将继续执行,当 https.get 返回响应时,回调函数将被执行。理想情况下,您想要对响应执行的任何操作都应该在回调函数中。

    文本变量的原始值为The session will be。然后你执行https.get,因为它是异步的,所以会移动到执行https.get之后的其他代码行并执行console.log("d" + text);文本的值仍然没有改变并打印旧值。现在https.get 返回成功响应并触发回调,现在文本值已更改,console.log("b" + text); 看到新值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 2019-01-23
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多