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

放肆的年华 提交于 2020-01-25 03:05:27

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/53068594/amazon-dynamodb-documentclient-get-use-values-outside-of-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!