node.js - Alexa 技能异步等待从 DynamoDB 获取数据

标签 node.js async-await amazon-dynamodb alexa alexa-skill

以下代码是我的 Alexa 技能中的启动处理程序,并且我的处理程序内部有一个名为 x 的变量。我试图将 x 设置为从 dynamoDB 获取的数据,并在 get 函数之外使用它(我从 https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.03.html#GettingStarted.NodeJs.03.02 获取该函数),以便 Alexa 可以读出 x 的值(字符串)(如您在返回中看到的那样)。我的“get”函数中的语句不会更改 get 函数本身之外的 x 值。我知道 get 函数内部的 x 实际上正在更改,因为我将其记录到控制台。所以我就此发布了一篇类似的文章,我最初认为这是一个范围问题,但事实证明这是因为 get 函数是异步的。因此,我添加了 async 和 wait 关键字,如下所示。我是 NodeJS 的新手,所以根据我的研究,我认为我应该把它们放在哪里。但这仍然不起作用。

const LaunchHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === `LaunchRequest`;
  },
  async handle(handlerInput) {
    var x;

    //DYNAMO GET FUNCTION
    await DBClient.get(params, function(err, data) {
    if (err) {
        console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
         x = data.Item.Answer;
    } }); 

    return handlerInput.responseBuilder
      .speak(x)
      .withShouldEndSession(false)
      .getResponse();
  },
};

顺便说一句,这是我(成功)从数据库返回的 JSON:

{
    "Item": {
        "Answer": "Sunny weather",
        "Question": "What is the weather like today"
    }
}  

最佳答案

您正在寻找这样的东西吗?在句柄函数中,我调用另一个函数 getSpeechOutput 来创建一些反馈文本。因此函数调用dynamodb函数getGA来获取用户数据

const getSpeechOutput = async function (version) {
  const gadata = await ga.getGA(gaQueryUsers, 'ga:users')

  let speechOutput;
  ...
  return ...
}

const UsersIntentHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === 'IntentRequest'
      && handlerInput.requestEnvelope.request.intent.name === 'UsersIntent';
  },
  async handle(handlerInput) {
    try {
      let speechOutput
     ...
        speechOutput = await getSpeechOutput("long");
     ...

      return handlerInput.responseBuilder
        .speak(speechOutput)
        .reprompt("Noch eine Frage?")
        .withSimpleCard(defaulttext.SKILL_NAME, speechOutput)
        .getResponse();

    } catch (error) {
      console.error(error);
    }
  },
};

这就是数据库函数:

const getUser = async function (userId) {
    const dynamodbParams = {
        TableName: process.env.DYNAMODB_TABLE_BLICKANALYTICS,
        Key: {
            id: userId
        }
    }
    return await dynamoDb.get(dynamodbParams).promise()
}

关于node.js - Alexa 技能异步等待从 DynamoDB 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192363/

相关文章:

amazon-web-services - 使用 DynamoDB 和 docClient,是否可以在使用 transactWrite 时获取返回值?

conditional - 有条件更新的 DynamoDBContext

MySQL where if 语句

node.js - node.js 上的 ClojureScript,代码

c# - 在等待 List<Task> 中的所有任务完成时显示进度

c# - 为什么任务甚至在等待中完成

amazon-web-services - DynamoDBMapper 有条件保存对象列表

node.js - 沿 node-express 应用程序传递和更新数据

node.js - Graphdb.js Node.js 一台server.repository通过Rest API连接多个查询

javascript - js如何循环发送多个请求