0

I am writing node js 10.x lambda function to put details into DynamoDB table.

Below is code

const AWS = require('aws-sdk');
var db = new AWS.DynamoDB.DocumentClient();
var tableName="xyz";

exports.handler = async (event) => {
    // TODO implement
    console.log("Event: "+ JSON.stringify(event));
    
    var response = {
        statusCode: 200,
        "headers": {
            "Access-Control-Allow-Origin" : "*",
            "Access-Control-Allow-Credentials" : true
        },
    };
    await db.put({
        TableName: tableName,
        Item: {
            userid: event.userid,
        }
    }, (error, data) => {      
        if (error) {
            console.log("error:"+ error);
        }
        else{
            console.log("Success");
        }
    }).promise();
    
    return response;
};

I am getting kind on random number of success return

Output execution 1

2019-11-07T07:03:45.388Z    f451dfc1-01ea-41d0-a998-945cb0f18be1    INFO    Success
2019-11-07T07:03:45.510Z    f451dfc1-01ea-41d0-a998-945cb0f18be1    INFO    Success
2019-11-07T07:03:45.511Z    f451dfc1-01ea-41d0-a998-945cb0f18be1    INFO    Success

Output execution 2

2019-11-07T07:08:19.270Z    3ce51f5d-bbbc-4dd6-b46f-2149ee9bb9cf    INFO    Success

Output execution 3

2019-11-07T07:08:27.410Z    2625bba5-b8e1-40e4-8704-7c0d486f6dff    INFO    Success
2019-11-07T07:08:27.431Z    2625bba5-b8e1-40e4-8704-7c0d486f6dff    INFO    Success

** does anyone know the cause of this problem?

I am relatively new to node js 10.x. so please help me if I have missed something in code **

Community
  • 1
  • 1
siddhesh padhye
  • 133
  • 1
  • 2
  • 10

1 Answers1

2

you are using a callback and promise at the same time, remove the callback.

You can try something like

exports.handler = async (event, context) => {
    const params = {
        TableName: tableName,
        Item: {
            userid: event.userid,
        }
    };

    try {
        const data = await dynamoDB.put(params).promise();
        console.log("Data: ", data);
    } catch(error) {
        console.error("Error:", error);
    }
}
Adiii
  • 54,482
  • 7
  • 145
  • 148