【问题标题】:Alexa skill async await fetching data from DynamoDBAlexa 技能异步等待从 DynamoDB 获取数据
【发布时间】:2019-08-07 02:37:39
【问题描述】:

以下代码是我的 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 和 await 关键字,如下所示。根据我的研究,我是 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"
    }
}  

【问题讨论】:

  • .get() 方法似乎正在接受回调,因此您必须将其包装在显式的 Promise 中以使其与 async/await 一起工作。但是快速浏览一下文档,看起来在你的方法末尾附加一个.promise() 应该会返回一个Promise,所以我会先尝试一下,看看它是否有效。类似于.get(params).promise()
  • 非常感谢你做到了!

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


【解决方案1】:

您正在寻找这样的东西吗?在句柄函数中,我调用另一个函数 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);
    }
  },
};

这就是 db 函数:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 2022-07-06
    • 1970-01-01
    • 2019-10-02
    • 2021-07-07
    • 2017-10-24
    相关资源
    最近更新 更多