简体   繁体   English

在AWS Lambda函数中使用S3中的JSON文件(用于Alexa)

[英]Using a JSON file from S3 in AWS Lambda function (for Alexa)

Context: I'm creating an Alexa skill using an AWS Lambda function, and have put a large JSON file in S3 rather than trying to put it in the Lambda function code itself. 上下文:我正在使用AWS Lambda函数创建Alexa技能,并将大型JSON文件放入S3中​​,而不是尝试将其放入Lambda函数代码本身中。 I have been trying to access the contents of the S3 file and assign it to a variable in the function so I can use it in the rest of the code, but it doesn't seem to be working properly. 我一直在尝试访问S3文件的内容,并将其分配给函数中的变量,以便可以在其余代码中使用它,但是它似乎无法正常工作。 See below for the relevant code, as well as what I can see when I print to console. 有关相关代码,以及在打印到控制台时所看到的内容,请参见下文。

Lambda function: Lambda函数:

var handlers = {

  'LaunchRequest': function() {

    var AWS = require('aws-sdk');
    var s3 = new AWS.S3();
    data = s3.getObject(myParams, function(err, data) {
        if(err) { console.log(err, err.stack);}
        else {
            console.log('First step');
            var fileText = data.Body.toString();
            console.log('Second Step' + fileText);
            return fileText;
        }
    });

    console.log('Third Step' + data);
  }
}

Console Output: 控制台输出:

Function Logs:
START Version: $LATEST
2017-12-29T23:59:38.585Z        Warning: Application ID is not set
2017-12-29T23:59:40.024Z        Third Step[object Object]
2017-12-29T23:59:40.159Z        First step
2017-12-29T23:59:40.183Z        Second Step[{category1: "test1", category2: "test2", category3: "test3"}]

Why does this code print the "Third Step", first? 为什么此代码首先打印“第三步”?

Remember that everything in node is async. 请记住,节点中的所有内容都是异步的。 getObject will return before it's callback is triggered. getObject将在触发回调之前返回。 Its return value is irrelevant; 它的返回值无关紧要; the response can only be accessed by the callback. 该响应只能由回调访问。

Move the this step to the callback, and you'll get the lines in the order you anticipated. 将这一步移至回调,您将按预期的顺序获得代码行。

If you find this to be unintuitive, you may prefer a more straightforward language like Python for your lambdas. 如果您觉得这不太直观,则可能更喜欢将更简单的语言(例如Python)用于lambda。 If you're committed to js, you may find the async library, especially the waterfall methodology, helpful. 如果您致力于js,则可能会发现async库(尤其是waterfall方法)很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM