Search code examples
javascriptnode.jsamazon-dynamodbaws-sdkalexa-skills-kit

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


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();

Solution

  • 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.