需要帮助使用 Lambda 和节点 Js 发布到 IoT 主题

Need help publishing to IoT topic using Lambda and node Js

我正在尝试使用 Amazon Alexa、IoT 和 Lambda 来控制我的树莓派。 到目前为止我的工作:

这是我的 node.js 脚本中的意图处理:

switch(event.request.intent.name) {
      case "testone":
        var config = {};
        config.IOT_BROKER_ENDPOINT      = "restAPILinkFromIoT".toLowerCase();
        config.IOT_BROKER_REGION        = "us-east-1";

        //Loading AWS SDK libraries
        var AWS = require('aws-sdk');
        AWS.config.region = config.IOT_BROKER_REGION;
        var iotData = new AWS.IotData({endpoint: config.IOT_BROKER_ENDPOINT});
        var topic = "/test";
        var output = "test output without publish"
        var params = {
            topic: topic,
            payload: "foo bar baz",
            qos:0
        };
        iotData.publish(params, (err, data) => {
            if (!err){
               output = "publish without error"
                this.emit(':tell', tell);
            } else {
                output = err
            }
        });
        context.succeed(
              generateResponse(
                buildSpeechletResponse(output, true),
                {}
              )
            )
        break;
        ...

脚本基本上应该 return "publish without error" 或错误消息。问题总是 returns "test output without publish"。发布函数(或至少回调函数)似乎从未被触发。我也没有在主题中看到消息。

我是不是做错了什么?

提前致谢!

这部分:

   iotData.publish(params, (err, data) => {
        if (!err){
           output = "publish without error"
            this.emit(':tell', tell);
        } else {
            output = err
        }
    });

是异步方法调用。 iotData.publish() 方法将立即 return。然后,一旦异步调用完成,带有 if(!err) ... 代码块的匿名回调函数将在未来某个时间执行。

也就是说这部分:

   context.succeed(
          generateResponse(
            buildSpeechletResponse(output, true),
            {}
          )
        )

在 IoT publish() 调用完成之前,并且在 output 变量有任何分配之前被调用。

要解决此问题,您可以将代码移至回调本身:

   iotData.publish(params, (err, data) => {
        if (!err){
           context.succeed(generateResponse(
            buildSpeechletResponse("publish without error", true),
            {});
          )
        } else {
           context.succeed(generateResponse(
            buildSpeechletResponse(err, true),
            {});            
        }
    });

附带说明一下,我真的不建议尝试同时学习 NodeJS 和 AWS Lambda 以及 IoT。如果您需要在学习 Lambda 和其他 AWS 东西的同时学习一门语言,我建议您选择 Python,因为您不必在 Python 中处理这些异步回调问题。