1

I know this question has been asked before, but I haven't been able to find a clear answer.

After retrieving data from my table in DynamoDB, I want to be able to store that data in a variable for use outside of the docClient function. I recognize that the way my code is set up, it tries to console.log() my userData variable before it finishes getting the data. I believe I need to use async/await, but I'm not sure how. I'm not very familiar with asynchronous JavaScript. Specific examples using this code would be very helpful. Thank you for looking at this for me!

var AWS = require('aws-sdk');
AWS.config.update({region: 'us-west-2'});
var docClient = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'});

var userData;

var params = {
 TableName: 'someTableName',
 Key: {'UserID': '1'}
};

docClient.get(params, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
    userData = data.Item;
  }
});

console.log(userData); // Output: undefined
janksmap
  • 61
  • 1
  • 2
  • 7
  • I suppose [this question](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) might be helpful. And yes, this question has been asked zounds times: [this one](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) is a direct duplicate, and I strongly suggest study its thread. – raina77ow Nov 14 '20 at 23:27
  • 2
    Related: https://stackoverflow.com/questions/51328292/how-to-use-async-and-await-with-aws-sdk-javascript – jarmod Nov 15 '20 at 00:04

1 Answers1

1

When calling docClient.get(...), also call .promise() on the returned value and wait for the asynchronous value via await. When the result is returned to you, the item data will be in the (possibly undefined) Item attribute. Finally, I expect you want to see what's in the object, so the code below inspects the result.

var params = {
    TableName: 'someTableName',
    Key: {'UserID': '1'}
};

const result = await docClient.get(params).promise();
const userData = result.Item;

console.log(util.inspect(userData));

All of the above must be done in an async function.

Peter Wagener
  • 2,073
  • 13
  • 20