1

How can I get data.Item.Name outside of docClient.get() to further use it in other functions.

const docClient = new awsSDK.DynamoDB.DocumentClient();

docClient.get(dynamoParams, function (err, data) {
    if (err) {
        console.error("failed", JSON.stringify(err, null, 2));
    } else {
        console.log("Successfully read data", JSON.stringify(data, null, 2));
        console.log("data.Item.Name: " + data.Item.Name);
    }   
});

// how can i use "data.Item.Name" here:

console.log(data.Item.Name);
return handlerInput.responseBuilder
    .speak(data.Item.Name)
    .getResponse();
mihai
  • 37,072
  • 9
  • 60
  • 86
Nicolas D
  • 15
  • 1
  • 7
  • Possible duplicate of [How can I access local scope dynamically in javascript?](https://stackoverflow.com/questions/598878/how-can-i-access-local-scope-dynamically-in-javascript) – 1stthomas Oct 30 '18 at 16:17
  • was my answer helpful? @NicolasD – mihai Dec 06 '18 at 08:20
  • i am new to dynamo db client. could you please post how you resolve this issue? not able to understand from the accepted answer – Dhana Mar 24 '20 at 22:07

1 Answers1

3

Welcome to asynchronous javascript.

Your options are to either:

  • continue your logic inside the callback
  • refactor your code to use async/await

I will give an example for the async/await option, however you will need some refactoring in other areas of your code, to support this.

async function wrapper() {
  const docClient = new awsSDK.DynamoDB.DocumentClient();

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

  var data = await docClient(dynamoParams);

  console.log(data.Item.Name);
  return handlerInput.responseBuilder
      .speak(data.Item.Name)
      .getResponse();
}

I assumed that your code lies in a function named wrapper. Note that you need to add the async keyword to this function.

It also returns a promise now, so to get the return value from wrapper you need to await it (in the part of the code where you're calling it). Which means that you need to add the async keyword to the top level function as well...and so on.

mihai
  • 37,072
  • 9
  • 60
  • 86
  • Sorry for the long delay. At the time I asked the question, I was unaware of async in javascript. Your answer would have definitely helped me back then. Thank you for clarification anyways! – Nicolas D Jan 03 '19 at 14:18
  • 1
    Now you can just do `var result = await docClient.get(dynamoParams).promise()` – Ally Aug 19 '20 at 08:12