I was testing some code. Locally it works. When I put it in a lambda it stops dead!
const AWS = require("aws-sdk");
const MyHandler = require("./handler.js");
// Initialise DynamoDB client outside of lambda for re-use
if (typeof docClient === 'undefined') {
var docClient = new AWS.DynamoDB.DocumentClient({region: "eu-west-1"})
}
exports.handler = async (event, context, callback) => {
context.dynamoDbClient = docClient;
await MyHandler.processEvent(event, context);
}
processEvent = (event, context) => {
console.log("Message received");
var params = {
TableName: "TestTable",
Item: {"test": "test"}
};
console.log("Inserting into dynamoDB");
try {
return context.dynamoDbClient.put(params, (error, data) => {
if (error) {
console.log("Error: Unable to insert DynamoDB: " + error);
} else {
console.log("Inserted into dynamoDB");
}
});
} catch (err) {
console.log("Error inserting to dynamoDB: " + e);
}
};
In the AWS logs, after Message received
I get nothing other than a END RequestId:...
.
You're using await
with a synchronous function processEvent
- this will resolve immediately; not wait.
Lambda will 'kill' unresolved promises, or in your case a callback, as soon as your handler returns. Whatever you're testing with locally may not do that, so although your handler function has returned, the callback gets executed in that environment (speculation).
Your problem is that you're mixing callbacks with Promises incorrectly. The AWS SDK exposes a promise option for almost all calls, so I suggest using that rather than writing your own:
processEvent = (event, context) => {
var params = {
TableName: "TestTable",
Item: {"test": "test"}
};
return context.dynamoDbClient.put(params).promise()
};