I'm very new to javascript in general and I'm doing a school project that builds a simple lambda function to save some data to DynamoDB from an HTTP request.
First, I had this version:
exports.handler = async (event) => {
var params = {
TableName: 'graph',
ReturnConsumedCapacity: "TOTAL",
Item: null
};
for (let input of event.inputs) {
params.Item = {
'key' : input.key,
'value' : input.value
};
await DynamoDB.DocumentClient.put(params, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("Success", data);
}
});
}
};
To my shallow understanding, an async function like the handler should wait for any await statement to finish executing, but I got nothing in the database. But even for some reasons if the lambda function execution didn't wait for DynamoDB.DocumentClient.put() to finish, wouldn't the DynamoDB.DocumentClient.put() finish on its own after the lambda has returned?
Then I followed some other people's examples and added promise() to the end:
exports.handler = async (event) => {
var params = {
TableName: 'graph',
ReturnConsumedCapacity: "TOTAL",
Item: null
};
for (let input of event.inputs) {
params.Item = {
'key' : input.key,
'value' : input.value
};
await DynamoDB.DocumentClient.put(params, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("Success", data);
}
}).promise();
}
};
Now even though it successfully put data into the database, the log shows 6 'Success' messages where I only put 3 pairs of key-value pairs. After some playing around, I realize the 'Success' messages appear once in the first callback, twice in the second, and three times in the third. I have no clues when it behaves like this at all. Can someone shed some light on this, please? Thank you