数据库获取完成之前,AWS Lambda Skill Handler返回

时间:2019-03-27 13:47:42

标签: aws-lambda alexa

我写了第一本Lambda来处理Alexa技能。

我的问题是对数据库的调用显然是异步的(我可以从Console.log消息出现在Cloud Log中的顺序看出来。

这是我的处理程序。 如何做到这一点,以便在从数据库中获取数据后返回?

const RemindMeHandler = {
   canHandle(handlerInput) {
     const request = HandlerInput.requestEnvelope.request;
     return request.type === 'LaunchRequest'
       || (request.type === 'IntentRequest'
          && request.intent.name === 'RemindMeIntent');
},
handle(handlerInput) {

   console.log('Started Reminder');

   var thing="Nothinbg";

/* ========== Read dB ========== */

   const params = 
   {
       TableName: 'ItemsToRecall',
       Key: {
          'Slot': {S: '1'}
         },
   };


   readDynamoItem(params, myResult=>
   {
      console.log('Reminder Results:  ' + myResult.data);

      thing="Captain";
      console.log('thing 1:  ' + thing);   
   });

   console.log('Ended Reminder');

   function readDynamoItem(params, callback) 
   {

       var AWS = require('aws-sdk');
       AWS.config.update({region: 'eu-west-1'});

       var docClient = new AWS.DynamoDB();

       console.log('Reading item from DynamoDB table');

       docClient.getItem(params, function (err, data) 
       {
          if (err) {
              callback(err, data);
           } else {
              callback('Worked', data);
           }
       });
}

/* ========== Read dB End ========== */
console.log('thing 2:  ' + thing);
return handlerInput.responseBuilder
  .speak(REMINDER_ACKNOWLEDGE_MESSAGE + thing)
  .getResponse();

}
};
/* ========== Remind Handler End  ========== */

1 个答案:

答案 0 :(得分:1)

您可以包装异步并返回一个Promise,然后使用async / await语法获取数据。您可以检查以下内容。请注意,它未经测试。

const RemindMeHandler = {
  canHandle(handlerInput) {
    return (
      handlerInput.requestEnvelope.request.type === "LaunchRequest" ||
      (handlerInput.requestEnvelope.request.type === "IntentRequest" &&
        handlerInput.requestEnvelope.request.intent.name === "RemindMeIntent")
    );
  },
  async handle(handlerInput) {
    console.log("Started Reminder");
    let thing = "Nothinbg";
    const params = {
      TableName: "ItemsToRecall",
      Key: {
        Slot: { S: "1" }
      }
    };
    const data = await readDynamoItem(params);
    console.log("Reminder Results:  ", data);
    thing = "Captain";
    let speechText = thing;
    return handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText)
      .getResponse();
  }
};

function readDynamoItem(params) {
  const AWS = require("aws-sdk");
  AWS.config.update({ region: "eu-west-1" });
  const docClient = new AWS.DynamoDB();
  console.log("Reading item from DynamoDB table");
  return new Promise((resolve, reject) => {
    docClient.getItem(params, function(err, data) {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}