簡體   English   中英

Alexa技能異步等待從DynamoDB提取數據

[英]Alexa skill async await fetching data from DynamoDB

以下代碼是我的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"
    }
}  

您是否正在尋找這樣的東西? 在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);
    }
  },
};

多數民眾贊成在db函數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM