Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling getItem() on DynamoDB object from AWS Lambda, why doesn't my callback execute?

I'm trying to get an item from my DynamoDB database. The way my code is presently written, I fail to retrieve any data from DynamoDB. I must be doing something wrong, because as far as I can tell from my test, my callback is not being called.

I spent all day on this yesterday and have been tinkering with it unsuccessfully since I woke up this morning.

If anyone can provide insight into what I'm doing wrong here, I would be very grateful. Thanks to everyone in advance!

Final note: The timeout on the Lambda function itself is set to 5 minutes. So I don't think the Lambda function is timing out before the db query can return. When I run the function, it exits after only a moment.

const AWS = require('aws-sdk');

const dynamodb = new AWS.DynamoDB();
var response = null;
var test = false;

function getFromDB(callback) {
  const params = {
    TableName: process.env['DB_TABLE_NAME'] // evaluates to 'test-table',
    Key: {
      "id": {
        S: postId // evaluates to a big string, pulling it in from an SNS message. Verified it with console.log(). It stores the expected value.
      }
    }
  };
  dynamodb.getItem(params, function(err, data) {
    if (err) callback(data, true);           // an error occurred
    else     callback(data, true);           // successful response
  });
}

getFromDB((data, isCalled) => {
    response = data;
    test = isCalled;
});

console.log(data); // evaluates to null
console.log(test); // evaluates to false
like image 561
Kevin Glick Avatar asked Mar 07 '23 10:03

Kevin Glick


2 Answers

I Had faced similar issue. I removed async in the statement below to resolve :

exports.handler = async (event,context) 
like image 199
fundoocoder Avatar answered Mar 09 '23 23:03

fundoocoder


I think what's going on is Lambda calls the function, but it's not going to wait for the call back, so it thinks it is done and exits.

I think I had a similar problem and resolved it by using Bluebird and async/await.

I can provide a snippet from my code if you need it

like image 34
Hassan Syyid Avatar answered Mar 10 '23 00:03

Hassan Syyid