数据库获取完成之前的 AWS Lambda 技能处理程序 returns

AWS Lambda Skill Handler returns before database Get is complete

我已经编写了我的第一个 Lambda 来处理 Alexa 技能。

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

这是我的处理程序。 我该如何做到 return 在从数据库获取数据后发生?

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  ========== */

您可以包装异步和 return 承诺,然后使用 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);
      }
    });
  });
}