简体   繁体   中英

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. 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. See below for the relevant code, as well as what I can see when I print to console.

Lambda function:

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. 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. If you're committed to js, you may find the async library, especially the waterfall methodology, helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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