Alexa技能异步等待从DynamoDB获取数据

问题描述 投票:1回答:1

以下代码是我的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"
    }
}  
node.js async-await amazon-dynamodb alexa alexa-skill
1个回答
0
投票

你在找这样的东西吗?在handle函数中,我调用另一个函数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()
}
© www.soinside.com 2019 - 2024. All rights reserved.