0

I'm doing some work on AWS DynamoDB and Lambda, I'm using lambda to get the dynamoDb table data. I'm getting it perfectly but I need to get that output to outside of the dynamoDb function and I need to save in a variable for another use.

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

const doClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'});

exports.handler = function(e, ctx, callback) {

    var params = {  
        TableName: 'table1',
        Key: { 
            "Device" : "123456",
            "Date_Time" : "2019-8-21"
        }
    };

    doClient.get(params, function(err, data) {
        if (err) {
            callback(err, null);
        } else {
            console.log(data);
            console.log(data.Item.Blue);
            var blue = data.Item.Blue;
            console.log(blue);
            return blue;
        }
    });

    //console.log(blue);   // how can get that blue value to here
};
congbaoguier
  • 985
  • 4
  • 20

1 Answers1

0

Promises in javascript work asynchronously it means your programs wont wait for "doClient.get" function to return before executing console.log(blue).

so you need to wait for function doClient.get to return the result your handler code will be like this

var params = {  
        TableName: 'table1',
        Key: { 
            "Device" : "123456",
            "Date_Time" : "2019-8-21"
        }
    };

docClient = require('util').promisify(doClient)

var blue = await docClient(params);

console.log(blue);

Amazon DynamoDB DocumentClient().get() use values outside of function

Nouman Khalid
  • 68
  • 1
  • 6