arkad
arkad

Reputation: 127

AWS lambda function firing twice when I click the Test button

I am using chrome browser and when I click the Test button in the top right side of my screen the lambda function seems to fire 1-3 times and I cannot figure out why this is happening.

I have tried putting the parameters directly into the dynamoDB.get call as well as googling for a while and trying to find someone with a similar issue. I found some that were close, but none that talk about a single function firing multiple times while using the built in test button. I have also tried making the call asynchronous and await it but all to no avail.

// Import Libraries
const aws = require('aws-sdk');
const dynamoDB = new aws.DynamoDB.DocumentClient();

aws.config.update({
    region: "us-east-1"
});

// Get Document
exports.handler = async (event, context) => {
    let params = {
       TableName: event.TableName,
        Key: {
            uuid: event.uuid
        } 
    };  

    return await dynamoDB.get(params, function(error, data){
        if(error){
            console.error("Error", error);
        }
        else{
            console.log("Data: ", data);
        }
    }).promise();
};

I would expect the function to call only once but it more often prints the same thing 2-3 times in the Execution Results area

Response:
{
  "Item": {
    "userId": "112",
    "uuid": "0118bb6f-e361-42a6-85e5-043091b69389"
  }
}

Request ID:
"4f5ce9da-bbf2-408b-9175-2759f45ba4fe"

Function Logs:
START RequestId: 4f5ce9da-bbf2-408b-9175-2759f45ba4fe Version: $LATEST
2019-11-06T01:46:01.361Z    4f5ce9da-bbf2-408b-9175-2759f45ba4fe    
INFO    Data:  { Item:
   {
       "userId": "112",
       "uuid": "0118bb6f-e361-42a6-85e5-043091b69389"
   } } 

2019-11-06T01:46:01.441Z    4f5ce9da-bbf2-408b-9175-2759f45ba4fe    
INFO    Data:  { Item:
   {
       "userId": "112",
       "uuid": "0118bb6f-e361-42a6-85e5-043091b69389"
   } } 
2019-11-06T01:46:01.461Z    4f5ce9da-bbf2-408b-9175-2759f45ba4fe    
INFO    Data:  { Item:
   {
       "userId": "112",
       "uuid": "0118bb6f-e361-42a6-85e5-043091b69389"
   } } 
END RequestId: 4f5ce9da-bbf2-408b-9175-2759f45ba4fe
REPORT RequestId: 4f5ce9da-bbf2-408b-9175-2759f45ba4fe  Duration: 127.68 ms Billed Duration: 200 ms Memory Size: 128 MB Max Memory Used: 95 MB  

Upvotes: 1

Views: 896

Answers (1)

jarmod
jarmod

Reputation: 78653

You are supplying a callback method and you are requesting a promise in the same API call.

You should not do both. I recommend removing the callback, for example:

exports.handler = async (event, context) => {
    const params = {
       TableName: event.TableName,
        Key: {
            uuid: event.uuid
        } 
    };

    try {
        const data = await dynamoDB.get(params).promise();
        console.log("Data: ", data);
    } catch(error) {
        console.error("Error:", error);
    }
};

Upvotes: 5

Related Questions