AWS Lambda 未将记录写入 AWS Aurora RDS

AWS Lambda not writing records to AWS Aurora RDS

我下面的代码不会从 lambda 向 RDS MySql table 写入任何内容。我可以肯定地说它进入了 if 条件,因为我可以在 CloudWatch 中看到它,而且我也没有看到任何错误。它也不会打印结果。

const AWS = require('aws-sdk');
const RDS = new AWS.RDSDataService({ apiVersion: '2018-08-01' });

exports.handler = async (event, context) => {
    var userId;
    var givenName;
    var count = 0;

    var params = {
        secretArn: 'secretArn',
        resourceArn: 'resourceArn',
        database: 'db',
        parameters: [{
                name: "userId",
                value: {
                    "stringValue": userId
                }
            },
            {
                name: "givenName",
                value: {
                    "stringValue": givenName
                }
            }
        ]
    };

    event.Records.forEach(async function (record) {
        count++;
        context.callbackWaitsForEmptyEventLoop = false;

        if (record.eventName == 'INSERT') {
            userId = record.dynamodb.NewImage.pk.S;
            givenName = record.dynamodb.NewImage.sk.S;
            console.log('userId - '+userId);
            console.log('givenName - '+givenName);
            params.sql = 'INSERT INTO Users (UserId, GivenName) VALUES(:userId, :givenName);'
            let result = await RDS.executeStatement(params).promise();
            console.log('Result -'+result);
        }

    });
console.log(count);
        return 'done';
    };

这是我的 CloudWatch 日志 -

您的 forEach 块中的承诺被忽略。

我建议保留一份承诺清单,然后等待所有承诺。

const promises = event.Records.map(async function (record) {
    count++;
    context.callbackWaitsForEmptyEventLoop = false;

    if (record.eventName == 'INSERT') {
        userId = record.dynamodb.NewImage.pk.S;
        givenName = record.dynamodb.NewImage.sk.S;
        console.log('userId - ' + userId);
        console.log('givenName - ' + givenName);
        params.sql = 'INSERT INTO users (userid, givenname) VALUES(:userid, :givenname);'
        let result = await RDS.executeStatement(params).promise();
        console.log('Result -' + result);
    }
});

await Promise.all(promises)