Shiva Burade
Shiva Burade

Reputation: 365

dynamodb putItem callback function not working

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler = async (event) => {

    var note = {};
    note.noteid = new Date().getTime();
    note.content = event.queryStringParameters["content"];

    var res = {};

    const response = {
        statusCode: 200,
        body: JSON.stringify(note),
    };

    var obj = {
        'TableName':'notes',
        'Item': {
          'note_id': {
            S: '2'
          },
          'name': {
            S: 'content'
          }
        },
        'ReturnConsumedCapacity': "TOTAL"
    };

    dynamodb.putItem(obj, function(err,result){
        console.log('function called!!');
        console.log(err);

        return response;
    });

};

My putItem is not working, the callback function is not being called. I have given full access to role of this user, but still function is not getting called.

Upvotes: 14

Views: 11097

Answers (2)

Jonathan Lee
Jonathan Lee

Reputation: 1432

Another possible reason for this error is because of one using AWS.DynamoDB.DocumentClient() instead of AWS.DynamoDB(); In that case, DocumentClient uses the put method instead of putItem

I kept checking the async and promise code when this was the cause

Upvotes: 3

Ricky Mo
Ricky Mo

Reputation: 7618

Assume you are using AWS Lambda. Since you are using the async/await pattern, the http response is eventually what async (event) => {} returns. In your case, that is nothing. You called putItem but did not wait for it. async (event) => {} return nothing immediately afterwards. Since the function has returned, your putItem call has no chances to callback.

You should convert the putItem call to promise and await for it. Then handle the result and return the http response.

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler = async (event) => {

    var note = {};
    note.noteid = new Date().getTime();
    note.content = event.queryStringParameters["content"];

    var res = {};

    const response = {
        statusCode: 200,
        body: JSON.stringify(note),
    };

    var obj = {
        'TableName':'notes',
        'Item': {
          'note_id': {
            S: '2'
          },
          'name': {
            S: 'content'
          }
        },
        'ReturnConsumedCapacity': "TOTAL"
    };

    try
    {
        var result = await dynamodb.putItem(obj).promise();
        //Handle your result here!
    }
    catch(err)
    {
        console.log(err);
    }
    return response;
};

Upvotes: 25

Related Questions