Amazon DynamoDB DocumentClient()。get()使用函数外部的值 [英] Amazon DynamoDB DocumentClient().get() use values outside of function

查看:93
本文介绍了Amazon DynamoDB DocumentClient()。get()使用函数外部的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 docClient.get()之外获取 data.Item.Name 以便在以下位置进一步使用

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


推荐答案

欢迎使用异步javascript。

Welcome to asynchronous javascript.

您可以选择以下任一方式:

Your options are to either:


  • 在回调中继续执行逻辑

  • 重构您的代码以使用异步/等待

我将举一个异步/等待选项的示例,但是您将

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

我假设您的代码位于名为的函数中包装器。请注意,您需要在该函数中添加 async 关键字。

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

它现在还返回一个承诺,因此从 wrapper 获取返回值,您需要 await (在调用它的代码部分中) )。这意味着您还需要在顶级函数中添加 async 关键字...等等。

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.

这篇关于Amazon DynamoDB DocumentClient()。get()使用函数外部的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆