lambda里面的s3.getObject并没有返回任何东西

时间:2016-09-10 19:22:23

标签: node.js amazon-web-services amazon-s3 lambda

我在lambda函数中有以下代码,这是一个Amazon echo技能:

"AMAZON.HelpIntent": function (intent, session, response) {
  var speechOutput ="Start";

  // Try S3
  var s3 = new AWS.S3({httpOptions: { timeout: 2000 }});
  var params = {
    Bucket: 'bucket',
    Key: 'file',
  };

  s3.getObject(params, function (err, data) {
    if (err) {
      // console.log(err, err.stack);
      speechOutput += "inside error";
      speechOutput += "Did not get it!" + err + ":===:" + err.stack;
    }
    else {
      speechOutput += "inside success";
      // console.log(data);
      speechOutput += "Got it! :" + data.Body.toString('ascii');
    }
  });

  speechOutput += " End. ";

  var repromptText = "Help reprompt.";
  response.ask(speechOutput, repromptText);
},

似乎非常直接......但是,当技能执行时,响应是这样的:

    {
          "version": "1.0",
          "response": {
            "outputSpeech": {
              "type": "PlainText",
              "text": "Start End. "
            },
            "shouldEndSession": false,
            "reprompt": {
              "outputSpeech": {
                "type": "PlainText",
                "text": "Help reprompt."
              }
            }
          },
          "sessionAttributes": {}
   }

换句话说,s3.getObject不会抛出任何错误,也不会运行。

lamda函数有' lambda_basic_execution'角色,在IAM中被定义为具有对S3的完全访问权限:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": "*"
    }
  ]
}

在S3内部,有一个存储桶(名为'存储桶')和文件(名为'文件')。可以从CLI和Web访问文件。存储桶和文件的权限设置为"每个人"。

请帮忙。

1 个答案:

答案 0 :(得分:4)

您没有等待S3通话完成。代码中的最后3行在调用s3.getObject()回调之前执行。尝试通过将最后3行移动到回调中来更改代码,如下所示:

"AMAZON.HelpIntent": function (intent, session, response) {
  var speechOutput ="Start";

  // Try S3
  var s3 = new AWS.S3({httpOptions: { timeout: 2000 }});
  var params = {
    Bucket: 'bucket',
    Key: 'file',
  };

  s3.getObject(params, function (err, data) {
    if (err) {
      // console.log(err, err.stack);
      speechOutput += "inside error";
      speechOutput += "Did not get it!" + err + ":===:" + err.stack;
    }
    else {
      speechOutput += "inside success";
      // console.log(data);
      speechOutput += "Got it! :" + data.Body.toString('ascii');
    }


    speechOutput += " End. ";

    var repromptText = "Help reprompt.";
    response.ask(speechOutput, repromptText);
  });
},