简体   繁体   中英

Lambda functions getItem call in NodeJS is not printing any item in console

I have a Lambda function named "Test-Lambda-with-DynamoDB" as below. It fetches an item in DynamoDB having Key as "1". The code is as below.

The function executes and I see below console output

START RequestId: d121f379-066e-4883-a115-8bbc2c1ab80f Version: $LATEST
END RequestId: d121f379-066e-4883-a115-8bbc2c1ab80f
REPORT RequestId: d121f379-066e-4883-a115-8bbc2c1ab80f  Duration: 5153.66 ms    Billed Duration: 5154 ms    Memory Size: 128 MB Max Memory Used: 86 MB  Init Duration: 138.01 ms

My Lambda functions (in NodeJS using SDK v2) code is as below --

exports.handler = async (event) => {
    // TODO implement

    var AWS = require("aws-sdk");

    // Set the region 
    AWS.config.update({region: 'ca-central-1'});

    // Create the DynamoDB service object
    var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

    // var docClient = new AWS.DynamoDB.DocumentClient();
    var table="whizlabcustomer";

    var params = {
        TableName: table,
        Key: {
            'ID': {S: '1'}
        }
    };

    ddb.getItem(params, function(err, data){
        if(err){
            console.log("Unable to read item. Error JSON: "+err);
        } else {
            console.log("Looks like a success!! ");
            console.log("GetItem succeeded: "+data.Item); 
        }
    });

};

I checked the CloudWatch metrics and did not observe any data point for Error count in the "Error count and success rate (%)" metric. I did not see any data points in "Async delivery failures". Any directions or pointers would be helpful.

The reason you aren't seeing either of your callbacks executed is because your lambda completes it's execution before the call to getItem completes. As it's currently written, your lambda doesn't wait for the call to getItem to complete.

Instead of using callbacks, you can use Javascripts async/await keyword. This will eliminate the need for callbacks and make sure your lambda waits for a response from getItem before exiting. For example:

try {
    const data = await ddg.getItem(params).promise()
    console.log("Yay, I have my data!")
    console.log(data)
} catch (err) {
  // do something else
}

Nearly all of the AWS SDKs return promises, so you can use this technique when talking to DynamoDB, S3, etc. Keep in mind that you'd use async/await instead of callbacks, never both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM