AWS Lambda 使用 s3 getObject 函数和 putItem 函数将其插入 DynamoDB 但没有任何反应

AWS Lambda using s3 getObject function and putItem function to insert it into DynamoDB but nothing happens

这是 node.js 代码:

'use strict';

const AWS = require("aws-sdk");

AWS.config.update({
    region: 'eu-west-1'});

const docClient = new AWS.DynamoDB.DocumentClient();

const tableName = 'Fair';

const s3 = new AWS.S3();

exports.handler = async (event) => {
    var getParams = {
        Bucket: 'dataforfair', //s3 bucket name
        Key: 'fairData.json' //s3 file location
    }
    
    const data = await s3.getObject(getParams).promise()
    .then( (data) => {
        //parse JSON 
        let fairInformations = JSON.parse(data.Body.toString());

        fairInformations.forEach(function(fairInformationEntry) {
            console.log(fairInformationEntry);
            var params = {
                TableName: tableName,
                Item: {
                    "year": fairInformationEntry.year,
                    "fairName":  fairInformationEntry.fairName,
                    "info": fairInformationEntry.info
                }
            };
        
            docClient.put(params, function(err, data) {
                console.log('*****test');
            if (err) {
                console.error("Unable to add fairInformation", fairInformationEntry.fairName, ". Error JSON:", JSON.stringify(err, null, 2));
            } else {
                console.log("PutItem succeeded:", fairInformationEntry.fairName);
            }
            });
        });
       })
       .catch((err) => {
           console.log(err);
       });
      

    const response = {
        statusCode: 200,
        body: JSON.stringify(data),
    };
    return response;
};

大家好,

我想在从 s3 存储桶中获取 JSON 文件后将数据放入 Dynamo DB。获得 JSON 和 console.log(fairInformationEntry);也仍然被触发,但是 docClient.put() 永远不会被调用。我没有收到任何错误,什么都没有。我不知道出了什么问题以及为什么它不起作用。我拥有合适的 IAM 角色,可以访问我需要的一切。

希望你能帮帮我!

问题是混淆了 promise、回调和 async/await。您还试图在 foreach 中执行异步操作。代码应该看起来像这样

"use strict";

const AWS = require("aws-sdk");

AWS.config.update({
  region: "eu-west-1"
});

const docClient = new AWS.DynamoDB.DocumentClient();

const tableName = "Fair";

const s3 = new AWS.S3();

exports.handler = async event => {
  var getParams = {
    Bucket: "dataforfair", //s3 bucket name
    Key: "fairData.json" //s3 file location
  };

  const data = await s3.getObject(getParams).promise();
  //parse JSON
  let fairInformations = JSON.parse(data.Body.toString());

  await Promise.all(
    fairInformations.map(fairInformationEntry => {
      console.log(fairInformationEntry);
      var params = {
        TableName: tableName,
        Item: {
          year: fairInformationEntry.year,
          fairName: fairInformationEntry.fairName,
          info: fairInformationEntry.info
        }
      };
      return docClient.put(params).promise();
    })
  );

  const response = {
    statusCode: 200,
    body: JSON.stringify(data)
  };
  return response;
};

希望对您有所帮助